在下面的代码中,
mac_str
是字符指针,mac
是uint8_t
数组:
sscanf(mac_str,"%x:%x:%x:%x:%x:%x",&mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]);
当我尝试上面的代码时,它给了我一个警告:
warning: format ‘%x’ expects argument of type ‘unsigned int *’, but argument 8 has type ‘uint8_t *’ [-Wformat]
但是我在他们指定的一些代码中看到了
sscanf(str,"%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",&mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]);
不会发出任何警告,但两者的工作原理相同。
使用
hhx
而不是仅仅使用x
有什么必要?
hh
是一个长度修饰符,指定参数的目标类型。转换格式说明符 x
的默认值为 unsigned int*
。加上 hh
,就变成 unsigned char*
或 signed char*
。
请参阅表格此处了解更多详情。
&mac[0]
是指向 unsigned char
的指针。1 %hhx
表示相应的参数指向 unsigned char
。对方孔使用方钉:格式字符串中的转换说明符必须与参数类型匹配。
1 实际上,
&mac[0]
是指向uint8_t
的指针,而%hhx
对于uint8_t
来说仍然是错误的。它在许多实现中“有效”,因为 uint8_t
在许多实现中与 unsigned char
相同。但正确的格式是 "%" SCNx8
,如:
#include <inttypes.h>
…
scanf(mac_str, "%" SCNx8 "… rest of format string", &mac[0], … rest of arguments);
hhx
将输入转换为 unsigned char,而 x
将输入转换为 unsigned int。由于 uint8_t
的 typedef 为 unsigned char
,因此 hhx
修复了警告。