Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Now handles two's compliment negative numbers, though I'm not convinced that it
- // handles the codes correctly, certainly not UTF-8 encoding.
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- // Forward declaration of function:
- int main();
- // Global variables:
- static char x[2]=" \0";
- static char buffer='\0';
- static char run=0;
- static char i=0;
- // This is used as a boolean so that the negative numbers are represented
- // correctly in binary:
- static char twoscompliment=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 (); might not work with Visual Studio 2010
- // but is fine with Code::Blocks):
- 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]);
- // Tests for negative numbers:
- if(x[0]<0)
- {
- twoscompliment=1;
- x[0]=x[0]+1;
- }
- else
- {
- twoscompliment=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 && !twoscompliment)
- {
- binary[i-1]='1';
- }
- else
- if (!a && !twoscompliment)
- {
- binary[i-1]='0';
- }
- else
- if (a && twoscompliment)
- {
- binary[i-1]='0';
- }
- else
- if (!a && twoscompliment)
- {
- binary[i-1]='1';
- }
- }
- // 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);
- if(twoscompliment)
- {
- printf("This is in two's compliment.\n");
- }
- printf("This reads as follows:\n");
- a=0;
- for(i=8; i>0; i=i-1)
- {
- printf("Bit %d is ",a);
- if(binary[i-1]=='1')
- {
- printf("TRUE\n");
- }
- else
- {
- printf("FALSE\n");
- }
- a=a+1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement