C語言16進制與ASCII字符相互轉換

1、把獲取到的16進制數據轉換成相同字符的ASCII字符,例:get[2] = {0x11,0x22};  →  put[4]={'1','1','2','2'};

數據的轉換主要通過sprintf();來完成的,對於該函數網上有許多講解,想要瞭解的可以查看一下。

typedef unsigned char uint8_t;
char data[64];
 
uint8_t *hex_to_ascii(uint8_t *str, uint32_t len)
{
    uint8_t *hex_buf = str;
    for (int i = 0; i < len; i++)
    {
        sprintf(&data[i * 2], "%02X", hex_buf[i]);
    }
    return (uint8_t *)data;
}

2、 把獲取到的ASCII字符轉換成相同字符的16進制,例:get[4]={'a','a','b','b'}; →  put[2] = {0xaa,0xbb};

ASCII轉換成16進制主要通過sscanf();來完成的。

typedef unsigned char uint8_t;
char data[64];
uint8_t *ascii_to_hex(char *str, uint32_t len)
{
    char *str_buf = str;
    uint8_t *hex = (uint8_t *)data;
    uint8_t data_buf[len];
    for (int i = 0; i < len; i++)
    {
        sscanf(str_buf, "%02x", (int *)&data_buf[i]);
        str_buf += 2;
    }
    memcpy(hex, data_buf, len);
    return hex;
}

3、把獲取到的16進制轉換成對應的ASCII字符,例:get[4]={'a','a','b','b'}; → put[4]={0x61,0x61,0x62,0x62};

typedef unsigned char uint8_t;
char data[64];
uint8_t *Char_to_Hex(char *str,uint32_t len)
{
    char *hex_buf = str;
    uint8_t *hex = (uint8_t *)data;
    for (int i = 0; i < len; i++)
    {
        if ((hex_buf[i] >= '0') && (hex_buf[i] <= '9'))        //0x30--0x39
            hex_buf[i] += 0x30;
        else if ((hex_buf[i] >= 'a') && (hex_buf[i] <= 'z'))   //0x61--0x66
            hex_buf[i] += 0x61;
        else if ((hex_buf[i] >= 'A') && (hex_buf[i] <= 'Z'))   //0x41--0x46
            hex_buf[i] += 0x41;
        else
            hex_buf[i] += 0xff;
    }
    memcpy(hex, hex_buf, len);
 
    return hex;
}

4、把獲取到的ASCII轉換成對應的16進制字符,例:get[4] = {0x61,0x61,0x62,0x62}; → put[4]={'a','a','b','b'};

typedef unsigned char uint8_t;
char data[64];
uint8_t *Hex_to_Char(char *str,uint32_t len)
{
    char *hex_buf = str;
    uint8_t *hex = (uint8_t *)data;
    for (int i = 0; i < len; i++)
    {
		if ((hex_buf[i] >= 0x30) && (hex_buf[i] <= 0x39))      //0--9
			hex_buf[i] -= 0x30;
		else if ((hex_buf[i] >= 0x41) && (hex_buf[i] <= 0x46)) //A--Z
			hex_buf[i] -= 0x37;
		else if ((hex_buf[i] >= 0x61) && (hex_buf[i] <= 0x66)) //a--z
			hex_buf[i] -= 0x57;
		else
			hex_buf[i] = 0xff;
    }
    memcpy(hex, hex_buf, len);
 
    return hex;
}

到此這篇關於C語言16進制與ASCII字符相互轉換的文章就介紹到這瞭,更多相關C語言16進制與ASCII字符轉換內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: