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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值