The code snippet
char c1;
char c2;
c1 = 0X7F;
c2 = 0X80;
printf("c1 = %X\nc2 = %X\n", c1, c2);
outputs
c1 = 7F
c2 = FFFFFF80
why is it that c2 does not print as 80? (i’m guessing it’s something to do with the fact that the most significant bit of 0X80 is 1 while the MSB of 0x7F is 0). how can i get c2 to print as simply 80?
Because
printfis a variadic function. Arguments to variadic functions undergo the default promotions; one effect of this is thatchararguments are converted toint. On your platform,charissigned, soc2is actually negative.printfis therefore printing all the leading ones that occur in theint(these are due to two’s-complement representation).There are (at least) 3 methods to work around this:
Use%02Xrather than%Xas yourprintfformat specifier.unsigned charrather thanchar(this gets promoted tounsigned int, so no leading ones)chars toint, and then mask:(int)c2 & 0xFF.[Note: The corollary of this is that the behaviour of
char c2 = 0x80is actually implementation-defined; ifcharissignedthen this will overflow.]