I am new to bitwise operation. I have the basic concepts of AND, OR, XOR, and 2s complement. However I came across following piece of code and am unable to figure out the output.
char c1 = 0xFF; // -1
int shifted = c1 << 8; //-256 (-1 * 256)
printf("%d, %x\n", shifted, shifted);
int myInt;
myInt = 0xFFFFFFE2;
printf("%d\n", myInt);
int i = 0xff;
printf("%d\n", i<<2);
The output is:
-256, ffffff00
-30
1020
Please help me understand what’s going on here!
c1is promoted tointfor the shift, so it’s still -1, shifting negativeints is implementation-defined, but your implementation seems to do like most and shifts it as if it were anunsignedbit-pattern, so a left-shift by eight places is multiplication by 256.as expected. The bit pattern of -256 in two’s complement is
0xFFFFFF00(32-bitints).That bit pattern is -30 in two’s complement
This is 255, 255*4 = 1020