On left shift of (char) 0xff by 8 and casting it to int we get -256 or 0xffffff00.
Can somebody explain why this should happen?
#include <stdio.h>
int main (void)
{
char c = 0xff;
printf("%d %x\n", (int)(c<<8),(int)(c<<8));
return 0;
}
Output is
-256 ffffff00
charcan be signed or unsigned – it’s implementation-defined. You see these results becausecharis signed by default on your compiler.For the signed char 0xFF corresponds to −1 (that’s how two’s complement work). When you try to shift it it is first promoted to an
intand then shifted – you effectively get multiplication by 256.So it is this code: