hh 和 h 格式说明符需要什么? [英] What is the need of hh and h format specifiers?
问题描述
在下面的代码中,mac_str
是字符指针,mac
是 uint8_t
数组:
In the code below mac_str
is char pointer and mac
is a uint8_t
array:
sscanf(mac_str,"%x:%x:%x:%x:%x:%x",&mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]);
当我尝试上面的代码时,它给了我一个警告:
When I try the above code it gives me a warning:
warning: format ‘%x’ expects argument of type ‘unsigned int *’, but argument 8 has type ‘uint8_t *’ [-Wformat]
但我在他们指定的一些代码中看到了
but I saw in some code they specified
sscanf(str,"%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",&mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]);
没有发出任何警告,但两者的工作方式相同.
which doesn't give any warning but both are working the same.
使用 hhx
而不是 x
有什么需要?
What's the need of using hhx
instead of just x
?
推荐答案
&mac[0]
是一个指向 unsigned char
的指针.1 %hhx
表示对应的参数指向一个unsigned char
.方孔使用方钉:格式字符串中的转换说明符必须与参数类型匹配.
&mac[0]
is a pointer to an unsigned char
.1 %hhx
means the corresponding arguments points to an unsigned char
. Use square pegs for square holes: the conversion specifiers in the format string must match the argument types.
1 其实&mac[0]
是一个指向uint8_t
的指针,而%hhx
uint8_t
仍然是错误的.它在许多实现中有效",因为 uint8_t
在许多实现中与 unsigned char
相同.但正确的格式是 "%" SCNx8
,如:
1 Actually, &mac[0]
is a pointer to a uint8_t
, and %hhx
is still wrong for uint8_t
. It "works" in many implementations because uint8_t
is the same as unsigned char
in many implementations. But the proper format is "%" SCNx8
, as in:
#include <inttypes.h>
…
scanf(mac_str, "%" SCNx8 "… rest of format string", &mac[0], … rest of arguments);
这篇关于hh 和 h 格式说明符需要什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!