Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need of hh and h format specifiers?

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.

What's the need of using hhx instead of just x?

like image 561
Siva Kannan Avatar asked Feb 14 '14 14:02

Siva Kannan


People also ask

Why do we need format specifiers?

The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.

What is hh modifier in C?

hh Specifies that a following d, i, o, u, x, or X. conversion specifier applies to a signed char. or unsigned char argument (the argument will.

What is %n format specifier?

%n is a format specifier used in printf() statement of the c language. It assigns a variable the count of the number of characters used in the print statement before the occurrence of %n . Note: %n does not print anything. Another print statement is needed to print the value of the variable which has the count.

Why are format specifiers used in control strings?

The format specifiers are used in C for input and output purposes. Using this concept the compiler can understand that what type of data is in a variable during taking input using the scanf() function and printing using printf() function.


1 Answers

&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);
like image 180
Eric Postpischil Avatar answered Sep 26 '22 09:09

Eric Postpischil