cmicrocontrollerlow-level-code

How to split hex byte of an ASCII character


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'

Solution

  • You can split each byte into two nibbles (4-bit quantities) using bitwise AND + shifts:

    unsigned char lo = byte & 0x0f;
    unsigned char hi = (byte >> 4) & 0x0f;
    

    Then, you can convert each half into a hex character by an array lookup (since strings are just character arrays):

    char loChar = "0123456789ABCDEF"[lo];
    char hiChar = "0123456789ABCDEF"[hi];