int to char casting
16,787
Solution 1
Endianness doesn't actually change anything here. It doesn't try to store one of the bytes (MSB, LSB etc).
- If
char
is unsigned it will wrap around. Assuming 8-bit char 259 % 256 = 3 - If
char
is signed the result is implementation defined. Thank you pmg: 6.3.1.3/3 in the C99 Standard
Solution 2
Since you're casting from a larger integer type to a smaller one, it takes the least significant part regardless of endianness. If you were casting pointers instead, though, it would take the byte at the address, which would depend on endianness.
So c = (char)i
assigns the least-significant byte to c
, but c = *((char *)(&i))
would assign the first byte at the address of i
to c
, which would be the same thing on little-endian systems only.
Author by
NeilPeart
Updated on July 17, 2022Comments
-
NeilPeart almost 2 years
int i = 259; /* 03010000 in Little Endian ; 00000103 in Big Endian */ char c = (char)i; /* returns 03 in both Little and Big Endian?? */
In my computer it assigns 03 to char c and I have Little Endian, but I don't know if the char casting reads the least significant byte or reads the byte pointed by the i variable.