Convert hex string to decimal
CRST1
Posts: 103
Hi, I have been searching all over and can't find the answer. Maybe I am missing something but here goes. I have a serial imput from an xbee. In the string it has the value of the adc channel as a hex string like 02F1 and CR . I can't figure how to convert the hex string to a decimal long variable. I have found the string to dec but I don't think that will work with hex strings will it?
Thanks for any help.
Thanks for any help.
Comments
Sometimes we can spend far more time trying to find the solution to a problem rather than solving it. In this case solving is very easy, starting with an initial result of zero, repeat 4 times or until a CR is detected - shift result left 4 bits (hex shift), subtract $30 from the next character and if the result > 9 then subtract 7 and add this to the result - after all this you will have the number.
I think I must be brain dead. I'm still a little confused with the shift method. If I have a string of 02F1 could you show me a code example of what you described? I can't seem to get it into my head.
RESULT = 0
REPEAT WHILE CH <> $0D
RESULT = RESULT <<4 (*16 or shift what we have at this point to the left one nibble (hex char) place )
N = CH-$30 (assuming we read the next character from the buffer)
IF N > 9 THEN N = N-7 ( this converts an ASCII 0-9 to 0..9 or an A-F (>9 after subtract) to $0A..$0F )
RESULT = RESULT + N ( since the right most nibble is zero because it has already been shift left 4 place all we need to do is insert the next nibble with a + )
So assuming we are converting 012F<cr> :
RESULT = 0
RESULT = 0 <<4
"0" - $30 --> 0 and it's not > 9
RESULT = 0+0 = 0
next character
RESULT = 0 << 4 = 0
"1" - $30 --> 1 and it's not > 9
RESULT = 0+1 = 1
next character
RESULT = 1 <<4 = $10
"2" - $30 --> 2 and it's not > 9
RESULT = $10+2 = $12
next character
RESULT = $12 << 4 = $120
"F" - $30 --> $16 and it's > 9 so subtract another 7 ---> $0F
RESULT = $120 + $0F = $12F
next character $0D terminates loop with RESULT = $012F
Thank you
Jonathan
IMO, it's a shame they made it a private method (as they did "RxCheck").
IMO, it's a nice bit of code.