Advertisement
Shaun_B

ASCII to binary converter

Feb 7th, 2012
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.38 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <conio.h>
  4. // Forward declaration of function:
  5. int main();
  6. // Global variables:
  7. // The \0 sequence is an escape character which I think means 'null' or end of string:
  8. static char x[2]=" \0";
  9. static char run=0;
  10. static char i=0;
  11. static int a=0;
  12. // This array of type char will represent each binary digit that is 'on':
  13. static char binary[8]="00000000";
  14. int main()
  15. {
  16.     // Clears screen and sets welcome message:
  17.     // system("cls"); works okay with Code::Blocks on Windows, but doesn't with Visual Studio
  18.     system("cls");
  19.     printf("Welcome to this ascii and binary conversion programme.\n");
  20.     printf("Please enter one character only and press the ENTER key.\n");
  21.     printf("Entering two or more characters may crash this programme,\n");
  22.     printf("or cause unusual results! (C) MMXII Donkeysoft.\n\n");
  23.     // Tells the main element of the program to start, ie, everything in the
  24.     // while() loop:
  25.     run=1;
  26.     while(run)
  27.     {
  28.         // Prompts for user input and gets the first two characters entered
  29.         // by the user and stores in x at location zero and one:
  30.         printf("\nEnter a character (press ENTER twice to exit)\nD:\\> ");
  31.         x[0]=getchar(); x[1]=getchar();
  32.         // Tests for condition to exit programme:
  33.         if(x[0]=='\n' || x[0]=='\0')
  34.         {
  35.             // Says goodbye and switches off boolean to run:
  36.             printf("\nGoodbye!");
  37.             run=0;
  38.             return 0;
  39.         }
  40.         // Outputs the character's ASCII value in decimal:
  41.         printf("Character value in decimal: %d\n",x[0]);
  42.         // Sets each bit as appropriate:
  43.         for(i=8;i>0;i=i-1)
  44.             {
  45.                 // Stores the remainder of x[0] modulo 2 into a, so it will be
  46.                 // either 1 or zero, and then divides x[0] by 2:
  47.                 a=x[0]%2;
  48.                 x[0]=x[0]/2;
  49.                 // Tests to see if a is true or not:
  50.                 if(a)
  51.                 {
  52.                     binary[i-1]='1';
  53.                 }
  54.                 else
  55.                     {
  56.                         binary[i-1]='0';
  57.                     }
  58.             }
  59.             // Now will output the contents of the character array called binary
  60.             // as a string, containing ones and zeros for each bit set:
  61.             printf("Character value in binary: %s\n",binary);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement