另一种选择是使用sscanf() 一次解析两个字符:
void convert(const char *s, uint8_t out[8])
{
memset(out, 0, 8);
while (sscanf(s, "%2"SCNx8, out++) == 1) {
s += 2;
}
}
第一行利用 64 位算法将 8 个字节设置为 0。然后我们从字符串 s 中扫描两个字符,从十六进制 ASCII 表示中读取一个 uint8_t 类型的整数。如果读取成功,我们将转到接下来的两个字符。
看起来像 code golf 提交,但很好,因为没有任何内容被复制。
另一个版本可能是:
void convert(const char *s, uint8_t out[8])
{
static char tbl[] = {
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
0, 1, 2, 3, 4, 5, 6,7,8,9,0,0,0,0,0,0,
0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
};
memset(out, 0, 8);
while (*s) {
*out++ = tbl[s[0]] * 16 + tbl[s[1]];
s += 2;
}
}