项目中需要用到HexToByte函数,当时已经下班了,心里有点慌张,就没实现。这下到了周末,就参考资料实现了一下:
首先是这个网站:
Arrays, How to correctly convert a Hex String to Byte Array in C? (w3guides.com)
下面是自己实现的代码,并做过测试:
#include <stdio.h>
int HexToBytes(const char* hexStr, unsigned int hexStrLen, unsigned char* bytes, unsigned int* pbytesLen)
{
if(hexStr == NULL || hexStrLen == 0)
{
return -1;
}
int length = hexStrLen / 2;
const char* pos = hexStr;
unsigned int byteval = 0;
for(unsigned int i = 0; i < length; i++) {
if (sscanf(pos + i * 2, "%2x", &byteval) != 1)
{
/* format error */
return -1;
}
bytes[i] = byteval;
}
*pbytesLen = length;
return 0;
}
void print(unsigned char* bytes, int bytesLen)
{
if(bytes == NULL || bytesLen == 0)
{
printf("Input Param is Invalid\n");
return;
}
for(unsigned int i = 0; i < bytesLen; i++) {
printf("%02x",bytes[i]);
}
printf("\n");
}
int main()
{
int ret = 0;
const char hexStr[] = "deadbeef10203040b00b1e50";
size_t hexStrLen = strlen(hexStr);
unsigned char bytes[512] = {0};
unsigned int bytesLen = 0;
ret = HexToBytes(hexStr, hexStrLen, bytes, &bytesLen);
if(ret == 0)
{
print(bytes, bytesLen);
}
return 0;
}
可能还有不足的地方,欢迎指正。