我有一个字符串,{F0A9B8BDE38182}
我需要将其转换为十六进制字节
0xF0 0xA9 0xB8 0xBD 0xE3 0x81 0x82
Run Code Online (Sandbox Code Playgroud)
我可以用下面的代码得到答案
for (i = 0; i < (str_len /2); i++)
{
sscanf(hexstring + 2*i, "%02x", &bytearray[i]);
printf("bytearray %d: %02x\n", i, bytearray[i]);
}
Run Code Online (Sandbox Code Playgroud)
但我不需要使用 sscanf
您需要将个人转换ASCII为相应的HEX数字,然后使用|以形成完整的byte.
例子:
for (i = 0; i < strlen(s)/2; i++)
{
bytearray[i] = AsciiToHex(s[2*i])<<4 | AsciiToHex(s[2*i+1]);
printf("bytearray %d: %02X\n", i, bytearray[i]);
}
uint8_t AsciiToHex(char c){
if (c >= '0' && c<='9') return c - '0';
else if (c >= 'A' && c <= 'F') return 10 + c - 'A';
else return 0;
}
Run Code Online (Sandbox Code Playgroud)