I recently came across this question, where the OP was having issues printing the hexadecimal value of a variable. I believe the problem can be summed by the following code:
#include <stdio.h>
int main() {
char signedChar = 0xf0;
printf("Signed\n”);
printf(“Raw: %02X\n”, signedChar);
printf(“Masked: %02X\n”, signedChar &0xff);
printf(“Cast: %02X\n", (unsigned char)signedChar);
return 0;
}
This gives the following output:
Signed
Raw: FFFFFFF0
Masked: F0
Cast: F0
The format string used for each of the prints is %02X, which I’ve always interpreted as ‘print the supplied int as a hexadecimal value with at least two digits’.
The first case passes the signedCharacter as a parameter and prints out the wrong value (because the other three bytes of the int have all of their bits set).
The second case gets around this problem, by applying a bit mask (0xFF) against the value to remove all but the least significant byte, where the char is stored. Should this work? Surely: signedChar == signedChar & 0xFF?
The third case gets around the problem by casting the character to an unsigned char (which seems to clear the top three bytes?).
For each of the three cases above, can anybody tell me if the behavior defined? How/Where?
I don’t think this behavior is completely defined by c standard. After all it depends on binary representation of signed values. I will just describe how it’s likely to work.
(char)0xf0which can be written as(char)-16is converted to(int)-16its hex representation is0xfffffff0.0xffis of typeintso before calculating&,signedCharis converted to(int)-16.((int)-16) & ((int)0xff)==(int)0x000000f0.(unsigned char)0xf0which can be written as(unsigned char)240is converted to(unsigned int)240as hex it’s0x000000f0