Question

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?

Was it helpful?

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.

OTHER TIPS

AFAIK, for Bitwise shift operators, Each of the operands shall have integer type. you should not use char type.

you will find the difference if you do this:

res = in << 6;
printf("%p %p \n",res,(in << 6));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top