what is the need of hh and h format specifiers?

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

what is the use of using hhx instead of x ,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 giving 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 dont give any warning

but both are working the same , what is the need of using hhx instead x,i searched in net but didnot get a direct answer

回答1:

&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 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); 


回答2:

hh is a length modifier that specifies the destination type of the argument. The default for conversion format specifier x is unsigned int*. With hh, it becomes unsigned char* or signed char*.

Refer to the table herein for more details.



回答3:

hhx converts input to unsigned char, while x converts to unsigned int. And since uint8_t is typedef to unsigned char, hhx fixes warning.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!