Consider the following:
unsigned int i1 = 0xFFFFFFFF;
unsigned char c1 = i1;
char c2 = i1;
printf("%x\n", i1); // 0xFFFFFFFF as expected
printf("%x\n", c1); // 0xFF as expected
printf("%x\n", c2); // 0xFFFFFFFF ????
printf("%d\n", c1 == c2); // false ????
I know, one should not assign an int
to a char
. Anyway, look how c2
seems to be storing more than a byte. What I expected was a copy of the "less significant byte" of n1
into c2
. Am I wrong to assume this? Is there no copy at all? Why does the behavior of unsigned char
differs from char
?
I actually found this in a very concrete situation while using gethostbyname(). It returns a struct which contains a field char *h_addr
storing an ipv4 address (four 8 bit long numbers). I wanted to print the ip address as numbers but got abnormally large results.
I know a workaround, masking with i1 & 0xFF
works but I would like to understand the issue.