What basically i want to do is
For eg: 'a' hex equivalant is 0x61
, can i split61
in to 6
and 1
and store them as '6'
and '1'
?
A buffer is receiving data like this:
rx_dataframe.data[0] is H'00,'.'// H' is Hex equivalant and '' is ASCII value
rx_dataframe.data[0] is H'31,'1'
rx_dataframe.data[0] is H'32,'2'
rx_dataframe.data[0] is H'33,'3'
I need to to convert hex values 0x00,0x31,0x32,0x33
in to char value '0','0','3','1','3','2';'3','3'
and to store them at the locations of tx_buff_data[];
I want my tx_buff_data
look like this
tx_buff_data[0] have H'30,'0'
tx_buff_data[1] have H'30,'0'
tx_buff_data[2] have H'33,'3'
tx_buff_data[3] have H'31,'1'
tx_buff_data[4] have H'33,'3'
tx_buff_data[5] have H'32,'2'
tx_buff_data[6] have H'33,'3'
tx_buff_data[7] have H'33,'3'
to convert you can do:
You can split each byte into two nibbles (4-bit quantities) using bitwise AND + shifts:
Then, you can convert each half into a hex character by an array lookup (since strings are just character arrays):
You can use sprintf to convert an integer value to a string, from the string you can then extract the individual chars.
Using the definition of the ASCII characters leads to an extremely time- and code saving solution. The ASCII-table shows that
Sometimes lower case letters are used for 'a' to 'f'.
So if the value of our nibble is below 10 (0000b to 1001b) the character representation would be 0x30 + n or, in c-syntax '0'+n.
If n is between 10 and 15 (1010b to 1111b) 0x41 + n - 10 or 'A'+n-10.
Using unsigned int 8bit instead of type char:
or shorter:
or as a macro (thanks to chqrlie for the (n) ):
If lower case letters should be used replace 'A' by 'a'.
Converting a byte with 2 nibbles to a 2-byte 0-terminated string you could use:
EDIT:
With correction of chqrlie to the macro, the function becomes more compact:
I propose you another variant, doing conversion of a fixed size input, and checking the size of the output:
As it is for a microcontroper, any overhead like sprintf() is avoided. You can call it like this: