Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 325
Balthasar Avatar asked Dec 12 '22 07:12

Balthasar


2 Answers

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.

like image 185
keshlam Avatar answered Jan 01 '23 23:01

keshlam


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));
like image 38
zzn Avatar answered Jan 02 '23 01:01

zzn