ASCII -> Binary
I am trying to construct a little C program which will allow you to type in ASCII values and then it automatically converts it to binary code. For example you would type in the words "you suck" and it is converted into the binary 011110010110111101110101 01110011011101010110001101101011
I know that I can declare each letters value in binary and then call that every time that letter is used but I was thinking that there may be an easier way to do this.
Any help? Oh and by the way this is for a unix system....
I'm not 100% certain about this, but I know that if you use printf to print a char as an int, the char's ascii value coes up. You might want to see if you can get something similar by using a binary conversion.
This will need tailoring to your needs but it will give you some idea....
void printbits(unsigned int tobeprinted)
unsigned int shift=8*sizeof(unsigned int)-1; // bits are 0-31 not 1-32
unsigned int mask=1<<shift;
printf("%i is ",tobeprinted);
for(unsigned int i=1;i<=(shift+1);i++)
if(tobeprinted &mask) printf("1");
tobeprinted <<= 1;
if (i%8==0) printf(" ");
I did this some months ago and posted the code on the board. It's very easy. Here are the basics (doesn't really matter what micro you're using either, or O/S, with a few exceptions)--
unsigned char myString = "Mary's lamb left her.\n"
'char' is a decimal value from 0-127 plus or minues. 'unsigned char' is how strings are really defined and are plus 0-255 (256 values in the ASCII alphabet).
On this board, I also posted complete sourcecode for printing an ASCII table.
an unsigned char is typedef'd by the compiler as an
So, get each byte, mask a bit and shift it. Like so:
i = 0;
while (i < strlen(myString))
a = ((myString[i] & 0x01)==1)?'1':'0';
Sorry for the errors, but I just got paged. this will give you a start.
I hope that works:
Oh sorry, I did a mistake:
You want to do it with a string, so take my algorithm and forget the scanf-function I wrote into the 5th line. You have to take a character-array.
Do it yourself!