Page 1 of 1
Convert ASCII to binary
Posted: Tue Oct 28, 2008 1:29 am
by MJU
I've got a TCP-IP flowcode that gets a value from a website via "GET".
I filter from this reply two ASCII characters that represent the state of my 8bit LED's.
So if I get C and 1 this must be HEX C1 and this must become 192 for the output for the LED's.
I've been trying the whole night, but my brains won't cooperate...
Is there anyone that can help me?
Thanks!
Re: Convert ASCII to binary
Posted: Tue Oct 28, 2008 9:42 am
by Steve
C1 is hex 193 - so I presume the 192 was a typo.
The technique is fairly simple:
1) Take the first character ("C"). If it's between 0 and 9, then keep it as it is. If it's between "A" and "F" then add 10 and take away 65 (this is the value of "A"). To do this a bit quicker, simply take away 55. (similarly, if it's between "a" and "f", take away 87). Put this value into a variable "msb".
2) Do the same thing to the second character ("1") and put the result into the variable "lsb".
3) The resulting value is equal to (16*msb) + lsb
If you're worried about how to take 55 from the letter "C", don't worry. "C" is stored as the ASCII value of 67, so 'C'-55 = 67-55 = 12. Therefore, the sum is (16*12)+1 = 193.
Re: Convert ASCII to binary
Posted: Tue Oct 28, 2008 7:06 pm
by MJU
I have had a little problem with your suggestion.
The HEX code I got is HEX.
This means that "1" is stored as 49 in the variable.
I know that my letters aren't capitals so I test if the value is ( a > 96 ) && ( a < 103 ).
If so, I subtract 87 from it.
If not, I subtract 48 from it.
In the first case I know if the value is the HEX-code for "a" until "f", if this is not true, this means that the value is HEX 0 to 9.
I could test if the value is a capital letter, and in this case I need to subtract 65 from the value.
What I learned is that I also need to subtract a value if the HEX is a figure.
Thanks for your help!
Re: Convert ASCII to binary
Posted: Sun Nov 02, 2008 10:47 am
by Steve
oops - I forgot that you'd need to also convert the '0' to '9' digit from ASCII to a real value! I'm glad you worked it out yourself.