Search code examples
c++cbit-manipulationbitwise-operatorsbit-shift

right-shifting unsigned char is filling with ones?


On my system, (unsigned char) -1 is (expectedly for chars of 8 bits) 1111 1111 in binary (255 decimal).

Similarly, (unsigned char) -1 >> 1 is as expected 0111 1111. The left was filled with a zero.

~((unsigned char) -1 >> 1) is 1000 0000 as expected.

Now I want to generate the unsigned char 0010 0000 for example.

I tried ~((unsigned char) -1 >> 1) >> 2, but this outputs 1110 0000 .... what the? Why is the left being filled with ones all of a sudden?


How can I generate an unsigned char with the nth bit (from the left) enabled?

I would like

n   unsigned char
0   1000 0000
1   0100 0000
2   0010 0000
3   0001 0000
... 
7   0000 0001

At the moment, ~((unsigned char) -1 >> 1) >> n is giving me

n   unsigned char
0   1000 0000
1   1100 0000
2   1110 0000
3   1111 0000
... 
7   1111 1111

This problem exists for uint8_t, uint16_t, but no longer happens at uint32_t and greater.


Solution

  • Another way to set the nth bit (from the left):

    1 << (CHAR_BIT - n - 1)