-1 in a 1byte variable is 1111 1111 now when I try to printf it as if It was an unsigned integer I expect it to be 255 but some how It's treating it as if It was 4bytes all containing ones saying "0xff ff ff ff" which is 2 to the 32 minus 1 . why is that? and why it assumes the remaining 3 bytes as all ones?
#include "stdio.h"
int main ( ) {
char g = -1;
printf ( "g is %u \n" , g );
return 0;
}
CodePudding user response:
For starters in your program the type char
behaves as the type signed char
.
In this call
printf ( "b is %u \n" , g );
the expression g
of the type char
is promoted to the type int
due to the integer promotions preserving the sign bit. The value -1 in an object of the type int for 2s complement system is represented like 0xff ff ff ff
provided that sizeof( int )
is equal to 4..
It will more correctly to write
printf ( "b is %u \n" , ( unsigned int )g );
To get the expected result you need to write
printf ( "b is %u \n" , ( unsigned char )g );
CodePudding user response:
When you use the %u
specifier with printf
you are telling it to expect an int
, which on your system is apparently 32-bits. So, -1
as a 32-bit int on your system is represented by 0xffffffff
.
It then prints this as an unsigned int, giving you the result you're seeing.
As mentioned in the comments, replace the %u
specifier with %hhu
to avoid the promotion of your 8-bit signed value into a 32-bit signed value.
For a list of C printf specifiers, see this page on cplusplus.com.
The %h
specifier indicates a short int
which is 16-bits. The %hh
specifier indicates a short short int
or just char
which is a single byte.