문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top