Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging bitshifts

Tags:

c++

I'm trying to exact 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?

like image 307
user4344 Avatar asked Mar 21 '26 04:03

user4344


2 Answers

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
like image 130
Benoit Avatar answered Mar 22 '26 17:03

Benoit


Your expression is evaluated using ints. Change it to:

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

and you should get the desired result.

like image 28
Paul R Avatar answered Mar 22 '26 16:03

Paul R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!