Shifting bits in an integer without changing the penultimate bit in C++?

ulak blade

Let's say I have some 32 bit integer:

000001010100010000100010001001 1 0

(The penultimate bit is bold/italic)

So if I shift it by 2 to the right I get:

00000001010100010000100010001001

Now the penultimate bit is lost. I thought of storing the original value and then using || (logical OR), but that would only work if the penultimate bit is set to 1. What if it's 0?

Mike Seymour

You'd want bitwise, not logical or; and to preserve the value, you'd need to clear the bit in the new value before inserting the one from the old value:

uint32_t const shift = 2; // number of bits to shift by
uint32_t const mask = (1 << 1); // set of bits to preserve

uint32_t bit_to_save = value & mask;
value >>= shift;
value &= ~mask;
value |= bit_to_save;

or, if you like brevity:

value = ((value >> shift) & ~mask) | (value & mask);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

bit shifting signed integer

From Dev

bit-shifting by an integer value

From Dev

bit, nibbles and shifting in C

From Dev

Shifting bit values in C

From Dev

Bit-shifting left and discarding bits

From Dev

Confused About Bit Shifting (Counting Bits in Byte)

From Dev

Changing integer bits

From Dev

Changing integer bits

From Dev

C - Bit Shifting is not working as expected

From Dev

Bit Shifting issue in C#

From Dev

Changing type without changing bits

From Dev

Java split the bits of a long in two parts using bit shifting

From Dev

Convert byte to sbyte without changing bits in C#

From Dev

Convert byte to sbyte without changing bits in C#

From Dev

Unexpected results while bit-shifting in C

From Dev

Big inputs(64 bits) giving unexpected results while Counting number of bits in a 64-bit integer in c++

From Dev

C code: left shift is shifting but dropping top bits

From Dev

What happen first, casting or shifting bits [C++]

From Dev

Convert C++ code (with pointers and bit shifting) to C#

From Dev

packing bits into an integer in C++

From Dev

packing bits into an integer in C++

From Dev

C# reversing the bits of an integer

From Dev

Set bit X of an integer to bit Y of another integer without branching?

From Dev

Flipping bits in an integer without bitwise operations

From Dev

C++ Assigning Enums explicit values using bit shifting

From Dev

Bit shifting difference in Java and C++ - how to reconcile

From Java

Bit shifting limit?

From Dev

Unexpected bit shifting result

From Dev

Is java bit shifting circular?