I want to convert two ASCII bytes to one hexadecimal byte. eg.
0x30 0x43 => 0x0C , 0x34 0x46 => 0x4F
...
The ASCII bytes are a number between 0
and 9
or a letter between A
and F
(upper case only), so between 0x30
... 0x39
and 0x41
... 0x46
I know how "to construct" 0x4F
with the numbers 0x34
and 0x46 : 0x4F = 0x34 * 0x10 + 0x46
So, in fact, i would to convert one ASCII byte in hexadecimal value.
For that, i can build and array to assign the hexadecimal value to the ASCII char :
0x30 => 0x00
0x31 => 0x01
...
0x46 => 0x0F
But, maybe it have a most « proper » solution.
The program will be run on an AVR µC and is compiled with avr-gcc
, so scanf()
/ printf()
solutions aren't suitable.
Have you got an idea ? Thanks
Here's a version that works with both upper and lower-case hex strings:
It's works, but could be much optimized !
The task:
Convert a string containing hexadecimal ascii characters to its byte values so ascii
"FF"
becomes0xFF
and ascii"10" (x31x30x00)
becomes0x10
// the final result should be:
//1. Firt step: convert asciiString so it contains upper cases only:
use:
//2. Convert a string containing hexadecimal ascii characters to its byte values:
//3. print result:
// use:
//4. The result should be:
0xAA 0xAA 0x12 0xFF
//5. This is the test program:
i can't make sense of your examples, but if you want to convert a string containing hexadecimal ascii characters to its byte value (e.g. so the string "56" becomes the byte 0x56, you can use this (which assumes your system is using ASCII)
You'd use it like e.g.
And res (which must be at least half the length of the
in
parameter) now contains the 2 bytes 0x12,0x34Note also that this code needs the hexadecimal letters A-F to be capital, a-f won't do (and it doesn't do any error checking - so you'll have to pass it valid stuff).
You can use
strtol()
, which is part of avr-libc, or you can write just your specific case pretty easily: