How do I convert a text string to a HEX string?
I have this 32 character string:
and I want to convert it into 16 HEX bytes into a byte buffer called Temp[40] so that Temp[0] = $cc, Temp[1] = $9a, Temp[2] = $67 and so on.
How do I do this?
Thanks.
Don
DAT
Text byte "cc9a67d9fb998b18922e015a35af0780"
and I want to convert it into 16 HEX bytes into a byte buffer called Temp[40] so that Temp[0] = $cc, Temp[1] = $9a, Temp[2] = $67 and so on.
How do I do this?
Thanks.
Don
Comments
pri hexConvert( fromPtr, toPtr, count) | i, t1, t2 repeat i from 0 to count-1 t1 := byte[fromPtr++] - "0" ' get most significant nibble and adjust for ASCII zero if t1 > 9 t1 := t1 - constant("a" - "0" - 10) ' if in range "a".."f", correct value for that t2 := byte[fromPtr++] - "0" ' get least significant nibble and adjust for ASCII zero if t2 > 9 t2 := t2 - constant("a" - "0" - 10) ' if in range "a".."f", correct value for that byte[toPtr++] := t1 << 4 + t2 ' put nibbles together into a byte and store
This can be done more efficiently, but the above is straightforward and easy to understanddat TestStr byte "cc9a67d9fb998b18922e015a35af0780", 0 pub main | idx term.start(RX1, TX1, %0000, 115_200) pause(10) ' press key to start term.rxflush term.rx ' convert array repeat idx from 0 to 15 buf[idx] := ascii_to_hex(@TestStr[idx << 1], 2) ' display term.tx(CLS) term.str(@TestStr) term.tx(CR) term.tx(CR) repeat idx from 0 to 15 term.hex(buf[idx], 2) term.tx(" ") repeat waitcnt(0) pub ascii_to_hex(p_str, n) : value | c '' Convert n hex ascii chars at p_str to value repeat n c := ucase(byte[p_str++]) c := lookdown(c: "0123456789ABCDEF") if (c > 0) value <<= 4 value += --c else quit return value pub ucase(c) '' Convert lowercase c to uppercase if ((c => "a") and (c =< "z")) c -= 32 return c
repeat i from 0 to 15 Temp[i] := lookdownz(byte[@Text][i*2+1]:"0123456789abcdef") Temp[i] += lookdownz(byte[@Text][i*2]:"0123456789abcdef")<<4