Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- // Forward declaration of function:
- int main();
- // Global variables:
- // The \0 sequence is an escape character which I think means 'null' or end of string:
- static char x[2]=" \0";
- static char run=0;
- static char i=0;
- static int a=0;
- // This array of type char will represent each binary digit that is 'on':
- static char binary[8]="00000000";
- int main()
- {
- // Clears screen and sets welcome message:
- // system("cls"); works okay with Code::Blocks on Windows, but doesn't with Visual Studio
- system("cls");
- printf("Welcome to this ascii and binary conversion programme.\n");
- printf("Please enter one character only and press the ENTER key.\n");
- printf("Entering two or more characters may crash this programme,\n");
- printf("or cause unusual results! (C) MMXII Donkeysoft.\n\n");
- // Tells the main element of the program to start, ie, everything in the
- // while() loop:
- run=1;
- while(run)
- {
- // Prompts for user input and gets the first two characters entered
- // by the user and stores in x at location zero and one:
- printf("\nEnter a character (press ENTER twice to exit)\nD:\\> ");
- x[0]=getchar(); x[1]=getchar();
- // Tests for condition to exit programme:
- if(x[0]=='\n' || x[0]=='\0')
- {
- // Says goodbye and switches off boolean to run:
- printf("\nGoodbye!");
- run=0;
- return 0;
- }
- // Outputs the character's ASCII value in decimal:
- printf("Character value in decimal: %d\n",x[0]);
- // Sets each bit as appropriate:
- for(i=8;i>0;i=i-1)
- {
- // Stores the remainder of x[0] modulo 2 into a, so it will be
- // either 1 or zero, and then divides x[0] by 2:
- a=x[0]%2;
- x[0]=x[0]/2;
- // Tests to see if a is true or not:
- if(a)
- {
- binary[i-1]='1';
- }
- else
- {
- binary[i-1]='0';
- }
- }
- // Now will output the contents of the character array called binary
- // as a string, containing ones and zeros for each bit set:
- printf("Character value in binary: %s\n",binary);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement