函数内容 HexString2Byte
。
参数解释
char* in 存放字符串十六进制的buf
int len buf长度
unsigned char* out 传出存放十六进制数字的数组
int HexString2Byte(char* in, int len, unsigned char* out)
{
int i = 0;
int j = 0;
unsigned char highByte = 0;
unsigned char lowByte = 0;
if (0 != len%2)
{
/* format error */
return -1;
}
for (i = 0; i < len; i+=2)
{
/* 先获取高位 */
if (('0' <= in[i]) && ('9' >= in[i]))
{
highByte = in[i]-0x30;
}
else if (('A' <= in[i]) && ('F' >= in[i]))
{
highByte = in[i]-55;
}
else if (('a' <= in[i]) && ('f' >= in[i]))
{
highByte = in[i]-87;
}
else
{
return -1;
}
/* 再获取低位 */
if (('0' <= in[i+1]) && ('9' >= in[i+1]))
{
lowByte = in[i+1]-0x30;
}
else if (('A' <= in[i+1]) && ('F' >= in[i+1]))
{
lowByte = in[i+1]-55;
}
else if (('a' <= in[i+1]) && ('f' >= in[i+1]))
{
lowByte = in[i+1]-87;
}
else
{
return -1;
}
out[j++] = highByte<<4 | lowByte;
}
return 0;
}
示例代码
#include <stdio.h>
#include <string.h>
int main()
{
char str[33] = {"A01A2479672573DF84537DF4C73D3FCC"};
unsigned char num[17] = {0};
int i = 0;
HexString2Byte(str, strlen(str), num);
printf("str:%s\n", str);
for (i = 0; i < sizeof(num); i++)
{
printf("%02X", num[i]);
}
printf("\n");
return 0;
}
运行结果
str:A01A2479672573DF84537DF4C73D3FCC
A01A2479672573DF84537DF4C73D3FCC00