16进制字符串转字节

使用C语言,将16进制格式的字符串如"1F",转换成单字节类型1F。
比如一个"1F2D34"的字符串,转成三个char字符,1F,2D,34

  1. 可以考虑使用strtol函数
//fucntion: transfer a hex string such as "1F" to unsigned char 1F
//param 1: source hex string that you need to transfer
//param 2: dest char addr
//return: success or not
bool hexstr2hex(char *str, unsigned char *dst)
{
    
    
	if(str == NULL || dst == NULL)
	{
    
    
		return false;
	}
	if(str+1 == NULL)
	{
    
    
		return false;
	}
	
	char num[3] = {
    
    0};
	sprintf_s(num, sizeof(num), "%c%c", str[0], str[1]);
	
	*dst = strtol(num, NULL, 16);
	return true;
}
  1. 可以使用sscanf函数
unsigned char code[6] = {
    
    0};
char string[13] = "1122334455FF";
int nLen = strlen(string);
for(int i=0; i<nLen; i+=2)
{
    
    
	sscanf(&string[i], "%02X", (unsigned int*)&code[i/2]);
}
for(int i=0; i<6; i++)
{
    
    
	printf("%c", code[i]);
}

输出的code为:
code[0]=11;
code[1]=22;
code[2]=33;
code[3]=44;
code[4]=55;
code[5]=FF;

猜你喜欢

转载自blog.csdn.net/csdn_zmf/article/details/122215843
今日推荐