Search code examples
coperator-precedence

Bit shift operator precedence in C


the bit shift operator in C is not operating as I expect, which without doubt is my misunderstanding, but can someone explain what's happening?

unsigned char in = 155;
unsigned char res;

res = (in << 6) >> 7;

should be the same as

res = in << 6;
res = res >> 7; // can also use res >>= 7;

but it's not.

The first result is:

in  = 10011011
res = 01001101

The second one (as expected):

in  = 10011011
res = 00000001

So it looks like in the first instance, it's operating each shift on the original data, instead of operating the first shift, then operating the second shift on the first result. Ideas?


Solution

  • Calculations are done in ints. In the second case, you're assigning to res, which will truncate to 8 bits, before shifting back. In the first case you aren't, so the truncation doesn't occur and the high bits are preserved and shifted back down.