字符串与十六进制数的相互转换

一、字符串转换为十六进制数

int convert_str_to_hex(uint8_t *str, int32_t str_len, uint8_t *out_str, int32_t *out_len)
{
    uint32_t i = 0 ;
    uint8_t ch1 = 0, ch2 = 0;
    if(str_len * 2 + 2 > *out_len)
    {
        return -1;
    }
    sprintf(out_str, "0x");
    
    for(i = 0; i < str_len; i++)
    {
        ch1 = (str[i] & 0xf0) >> 4;
        ch2 = (str[i] & 0x0f);

        ch1 += ((ch1 > 9) ? 0x57 : 0x30);
        ch2 += ((ch2 > 9) ? 0x57 : 0x30);

        out_str[2*i + 2] = ch1;
        out_str[2*i + 3] = ch2;
    }

    out_str[str_len * 2 + 2] = 0;
    *out_len = str_len * 2 + 2;

    return 0;
}    

 

二、十六进制数转换为字符串

int convert_hex_to_str(uint8_t *src, uint32_t len, uint8_t *dest)
{
    uint32_t i = 0 ;
    uint8_t ch1, ch2;
    if(len % 2 != 0)
    {
        printf("%s,%d - in convert_hex_to_str(), len:%u % 2 != 0!\n", __FILE__, __LINE__,len);
        return -1;
    }
    
    for(i = 0; i < len/2; i++)
    {
        ch1 = src[i*2];
        ch2 = src[i*2+1];

        ch1 -= ((ch1 > (9+0x30)) ? 0x57 : 0x30);
        ch2 -= ((ch2 > (9+0x30)) ? 0x57 : 0x30);

        dest[i] = (ch1<<4)|ch2;
    }

    return 0;
}

 

posted @ 2020-03-31 13:08  XNQC  阅读(1247)  评论(0编辑  收藏  举报