I'm trying to work with bit manipulation, and am struggling modifying the bits directly.
I have something as follows:
unsigned char myBits = 128; // 10000000 in binary
myBits = myBits >> 1; // Right shift, so we get 64, or 01000000 in binary
Now, how would I use bit manipulation to modify the first bit after the right shift (01000000) to a 1 (11000000)?
CodePudding user response:
Most implementations will shift a "1" bit in from the left if the type in question is signed and the value is negative.
So you could either change the type to signed char
, or do some casting on the unsigned types:
myBits = (unsigned char)((signed char)myBits >> 1);
CodePudding user response:
you need to binary OR it with the shifted value:
myBits |= myBits >> 1;
https://godbolt.org/z/dY3eY5dc5
To set the most significant bit (you can change the type to any integer type and it will work):
myBits |= 1ULL << (sizeof(myBits) * CHAR_BIT - 1);