Reputation: 70223
The program:
#include <stdio.h>
#include <limits.h>
int main( void )
{
#ifdef __CHAR_UNSIGNED__
printf( "%d\n", __CHAR_UNSIGNED__ );
#endif
printf( "%d\n", CHAR_MAX );
printf( "%d\n", CHAR_MIN );
printf( "%hhd\n", CHAR_MAX );
}
Output (on my x86_64 desktop):
127
-128
127
That is as expected. Now, I ran the same on a Raspberry Pi (ARM):
1
255
0
-1
So... apparently I have misunderstood some step CHAR_MAX
is taking in its way to output, as the output I was expecting in that last line -- passing CHAR_MAX
to %hhd
on a machine with char
being unsigned -- would have been 255
.
(And if you should ask, the result is the same for (char)CHAR_MAX
, and (unsigned char)CHAR_MAX
.)
What am I missing?
This happened to me during regression testing my own printf()
implementation on the Raspberry Pi -- which, by the way, does print 255
. So... only one implementation is doing it right, and I have the sinking feeling it's not mine...
Upvotes: 1
Views: 7084
Reputation: 409136
The format "%hhd"
is for a signed byte. If you pass an unsigned byte then you technically have undefined behavior. To print an unsigned byte you need to use "%hhu"
.
What really happens is because of how two's complement integers work, and that 0xff
is equal to -1
.
Upvotes: 8