I am trying to print char as positive value:
char ch = 212;
printf(\"%u\", ch);
but I get:
4294967252
How
This is because in this case the char
type is signed on your system*. When this happens, the data gets sign-extended during the default conversions while passing the data to the function with variable number of arguments. Since 212 is greater than 0x80, it's treated as negative, %u
interprets the number as a large positive number:
212 = 0xD4
When it is sign-extended, FF
s are pre-pended to your number, so it becomes
0xFFFFFFD4 = 4294967252
which is the number that gets printed.
Note that this behavior is specific to your implementation. According to C99 specification, all char
types are promoted to (signed) int
, because an int
can represent all values of a char
, signed or unsigned:
6.1.1.2: If an
int
can represent all values of the original type, the value is converted to anint
; otherwise, it is converted to anunsigned int
.
This results in passing an int
to a format specifier %u
, which expects an unsigned int
.
To avoid undefined behavior in your program, add explicit type casts as follows:
unsigned char ch = (unsigned char)212;
printf("%u", (unsigned int)ch);
char
up to the implementation. See this question for more details.