如何左移一位特定的位?

Dri*_*ter 1 c c++ bit-manipulation

我想在离开它的位置的特定位置只左移一位0,所以我不想用<<运算符移动整个变量,这是一个例子:假设变量有值1100 1010,我想移动第四位然后结果应该是1101 0010

R S*_*ahu 6

到达那里的步骤。

  1. 从原始数中拉出位值。
  2. 将位值左移一位。
  3. 将位移后的值合并回原始数字。
// 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.
Run Code Online (Sandbox Code Playgroud)