-
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....
:o
-
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.
starX
www.axioftime.com
-
This will need tailoring to your needs but it will give you some idea....
Code:
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");
else
printf("0");
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
unsigned byte
So, get each byte, mask a bit and shift it. Like so:
int a,i;
i = 0;
while (i < strlen(myString))
{
for(j=0;j<8;j++)
{
a = ((myString[i] & 0x01)==1)?'1':'0';
myString[i]>>=1;
count(a);
};
};
Sorry for the errors, but I just got paged. this will give you a start.
enjoy.
-
Hi!
I hope that works:
Code:
int asc,count1,count2;
int max=2;
scanf("%d",&asc);
for(count1=8;count>0;count1--)
{
for(count2=0;count2<count1;count2++,max*=max) ;
if(asc>=max)
{
printf("1");
asc-=max;
}
else printf("0");
}
klausi
-
correction
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!
Sorry,
klausi