1.背景
有时会出现这样一种情景:我们需要接收十六进制数用于数据处理,但收到的不是hex而是字符类型,
即想要的是0x8c
而收到的是0x38 0x63
("8"和“c”对应的ASCII码),这时便需要对其进行转化。

2.代码
/**
* OS:windows 10
* IDE:VS2021
* Language:c/c++
*/
#include "stdio.h"
#include "string.h"
int HexStr2HexNum(char* HexStrArray, int len, unsigned char* HexNumArray);
int main(){
char str1[] = "8c5def";
//char str1[] = "F95dev"; //you can check with this wrong format hex string
char* str = str1;
unsigned char HexNumArray[3];
int num = HexStr2HexNum(str, strlen(str), HexNumArray);
if (num == 0)
{
for (int i = 0; i < sizeof(HexNumArray); i++)
printf("%x ", HexNumArray[i]);
printf("\n");
}
}
/**
* @brief Convert hex String to hex number.
* @param HexStrArray: pointer to the hex string array
* @param len: length of the hex string.
* @param HexNumArray: pointer to the hex number array
* @retval Function status
This parameter can be one of the following values:
@arg 0:The conversion run correctly.
@arg -1:The conversion run incorrectly.
*/
int HexStr2HexNum(char* HexStrArray, int len, unsigned char* HexNumArray)
{
int j = 0;
for (int i = 0; i < len; i += 2)
{
char HIGH_BYTE=0;
char LOW_BYTE=0;
//high 4
if (HexStrArray[i] > 0x30 && HexStrArray[i] < 0x3A)
{
HIGH_BYTE = HexStrArray[i] - 0x30;
}
else if (HexStrArray[i] > 0x41 && HexStrArray[i] < 0x47)
{
HIGH_BYTE = HexStrArray[i] - 0x37;
}
else if (HexStrArray[i] > 0x61 && HexStrArray[i] < 0x67)
{
HIGH_BYTE = HexStrArray[i] - 0x57;
}
else
{
printf("Please make sure the format of Hex String is correct!\r\n");
printf("The wrong char is \"%c\", and its number is % d\r\n", HexStrArray[i],i);
return -1;
}
//low 4
if (HexStrArray[i + 1] > 0x30 && HexStrArray[i + 1] < 0x3A)
{
LOW_BYTE = HexStrArray[i + 1] - 0x30;
}
else if (HexStrArray[i + 1] > 0x41 && HexStrArray[i + 1] < 0x47)
{
LOW_BYTE = HexStrArray[i + 1] - 0x37;
}
else if (HexStrArray[i + 1] > 0x61 && HexStrArray[i + 1] < 0x67)
{
LOW_BYTE = HexStrArray[i + 1] - 0x57;
}
else
{
printf("Please make sure the format of Hex String is correct!\r\n");
printf("The wrong char is %c ,and its number is %d\r\n", HexStrArray[i+1], i+1);
return -1;
}
HexNumArray[j] &= 0x0F;
HexNumArray[j] |= (HIGH_BYTE << 4) ;
HexNumArray[j] &= 0xF0;
HexNumArray[j] |= LOW_BYTE;
j++;
}
return 0;
}