Can anyone explain why the following code outputs what it does:
char c = -1;
cout << (c << 8) << endl;
cout << ((unsigned char) c << 8) << endl;
cout << (c << 24) << endl;
cout << ((unsigned char) c << 24) << endl;
Output:
-256
65280
-16777216
-16777216
I thought casting to an unsigned char would simply change the way the bits get interpreted. However, it’s changed the results when shifting to the left by 8. What’s strange is that this doesn’t seem to be the case when shifting to the left by 24.
In each case, the character gets promoted to
intbefore the shift.On your platform,
charis signed, socis-1, but(unsigned char)(c)is 255.So you are seeing:
-1 << 8255 << 8-1 << 24255 << 24Note that the latter overflows and wraps (on your platform). It is different from
255U << 24, which is 4278190080. To achieve that, you have to say(unsigned int)(unsigned char) c << 24.