Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shift left one specific bit?

I want to shift left only one bit in a specific place leaving its position 0, so I do not want to shift the whole variable with << operator, here is an example: say the variable has the value 1100 1010 and I want to shift the fourth bit then the result should be 1101 0010.

like image 775
Drifter Avatar asked Mar 20 '26 14:03

Drifter


2 Answers

Steps to get there.

  1. Pull out bit value from the original number.
  2. Left shift the bit value by one.
  3. Merge the bit-shifted value back to the original number.
// Assuming C++14 or later to be able to use the binary literal integers
int a = 0b11001010;  
int t = a & 0b00001000;  // Pull out the 4-th bit.
t <<= 1;                 // Left shift the 4-th bit.
a = a & 0b11100111;      // Clear the 4-th and the 5-th bit
a |= t;                  // Merge the left-shifted 4-th bit.
like image 115
R Sahu Avatar answered Mar 22 '26 06:03

R Sahu


For C++, I'd just use a std::bitset. Since you set the bit of pos + 1 to the value of the bit at pos, and then set the bit at pos to 0 this translate into bitset code that is quite easy to read. That would give you a function like

unsigned char shift_bit_bitset(unsigned char val, unsigned pos)
{
    std::bitset<8> new_val(val);
    new_val[pos + 1] = new_val[pos];
    new_val[pos] = 0;
    return new_val.to_ulong();
}
like image 28
NathanOliver Avatar answered Mar 22 '26 04:03

NathanOliver



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!