signed char num = 220; //DC in hex
printf("%02X\n", num);
printf("%d\n", num);
I know that signed char can only represent -128~127,but why the above outputs:
FFFFFFDC
-36
What’s the reason?
UPDATE
My above code is just contrived for my question,that is ,what happens when we cast signed char to int/hex
As our starting point, 220 = DC in hex, and 11011100 in binary.
The first bit is the sign-bit, leaving us with 1011100. Per two’s complement, if we complement it (getting 0100011), and then add one, we get 0100100 — this is 36.
When it converts the signed char to signed int, it doesn’t say “this would be 220 if it’s unsigned”, it says “this is -36, make it an int of -36”, for which the 32-bit two’s complement representation is FFFFFFDC, because it must be the negative value for the full size of int (this is called sign-extension):
Or, in hex,
FFFFFFDC.This is why you must be careful with
printf("%x", ch);(and relatives) — if you intend to just get a two-digit value, and chars are signed, you may wind up with eight digits instead. Always specify “unsigned char” if you need it to be unsigned.