开发者

Merging bitshifts

I'm trying to exa开发者_如何学Pythonct a 3 bit value from a byte for example:

unsigned char r = ((253 << 5) >> 5);

Result value should be 5 but why does it returns 253?


Two possibilities:

  • Your expression is evaluated as an integer and cast as a sngle-byte value in the end.
  • your compiler optimizes away the shift operations.

Note that your result should be 5, not 3. What you want is:

const unsigned char c = 253 & 0x07 ; // (00000111)

Your bit mask is:

253 | 1 1 1 1 1 1 0 1 | F D
  7 | 0 0 0 0 0 1 1 1 | 0 7
+++++++++++++++++++++++++++
  5 | 0 0 0 0 0 1 0 1 | 0 5


Your expression is evaluated using ints. Change it to:

unsigned char r = ((unsigned char)(253 << 5) >> 5);

and you should get the desired result.


Because of integer promotion. There is nothing in the expression 253 << 5 that limits it to work in a byte only; the type of the literal 253 is int.

You need to add casts, or (better, in my opinion) extract using a mask. To get the lowest-three bits from an integer, simply use:

const unsigned char r = 253 & ~((1 << 3) - 1);

This works because 1 << 3 is 810, which in binary is 000010002. We subtract one, to get 710 or 000001112. We invert this, to get a mask that includes everything but the three right-most bits, i.e. 111110002. This is then bitwise-anded with the value to do the extraction.

Above, I show the binary values using 8 bits only, extend on the left with zeroes up to your platform's int size since the above is done using int precision.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜