简体   繁体   中英

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 .

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.

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();
}

Maybe not the shortest/cleanest way, but this'll do it:

unsigned shift_bit = 4;
unsigned char val = 0xCA; // 1100 1010

unsigned char bit_val = val & (1 << shift_bit - 1); // Get current bit value
val = val & ~(1 << shift_bit - 1);                  // Clear initial bit location
val = bit_val ?                                     // Update next bit to 0 or 1
        val | (1 << shift_bit) : 
        val & ~(1 << shift_bit);

See it work with the test cases specified in your question and comments here: ideone

A simpler way is

(x & 0b11101111) + (x & 0b00001000)

that is, clear the bit that will be shifted into and add the bit to be shifted, which will overflow to the left if it is 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM