Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the format specifier for uint8_t and uint16_t the same (%u)? [duplicate]

I only found pretty unrelated questions due to the tons of results searching for printf().

Why does uint8_t not specify its own format string but any other type does?

As far as I understand printf(), it has to know the length of the supplied parameters to be able to parse the variable argument list.

Since uint8_t and uint16_t use the same format specifier %u, how does printf() "know" how many bytes to process? Or is there somehow an implicit cast to uint16_t involved when supplying uint8_t?

Maybe I am missing something obvious.

like image 741
Rev Avatar asked Oct 14 '14 13:10

Rev


People also ask

What is the format specifier for uint8_t?

Since uint8_t and uint16_t use the same format specifier %u , how does printf() "know" how many bytes to process?

What is the meaning of uint8_t?

A UINT8 is an 8-bit unsigned integer (range: 0 through 255 decimal).

What is the format specifier for long long int in C?

Long Int Format Specifier %ld The %ld format specifier is implemented for representing long integer values. It is implemented with the printf() function for printing the long integer value stored in the variable.


2 Answers

Because %u stands for "unsigned", it well may be uint64_t and is architecture dependent. According to man 3 printf, you may want to use length modifier to get sought behaviour, i.e. %hu (uint16_t) and %hhu (uint8_t).

like image 75
wick Avatar answered Oct 12 '22 03:10

wick


printf() is a variadic function. Its optional arguments( and only those ) get promoted according to default argument promotions( 6.5.2.2. p6 ).

Since you are asking for integers, integer promotions are applied in this case, and types you mention get promoted to int. ( and not unsigned int because C )

If you use "%u" in printf(), and pass it an uint16_t variable, then the function converts that to an int, then to an unsigned int( because you asked for it with %u ) and then prints it.

like image 42
2501 Avatar answered Oct 12 '22 05:10

2501