How to split hex byte of an ASCII character

2019-05-11 06:07发布

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'

7条回答
地球回转人心会变
2楼-- · 2019-05-11 06:26

Here is a sample program that can be used as a template for your code

#include <stdio.h>

int main(void) 
{
    char in[] = { '\0', '1', '2', '3' };
    char out[2 * sizeof( in )];
    size_t  i;
    char *p;

    p = out;
    for ( i = 0; i < sizeof( in ) / sizeof( *in ); i++ )
    {
        *p = ( ( unsigned char )in[i] & 0xF0 ) >> 4;
        *p +=( *p < 10 ) ? '0' : 'A' - 10;
        ++p;
        *p = ( ( unsigned char )in[i] & 0x0F );
        *p +=( *p < 10 ) ? '0' : 'A' - 10;
        ++p;
    }

    for ( i = 0; i < sizeof( out ) / sizeof( *out ); i++ )
    {
        printf( "%c", out[i] );
    }

    puts( "" );

    return 0;
}

The output is

00313233
查看更多
登录 后发表回答