首页 > 解决方案 > 如何左移一位特定的位?

问题描述

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

标签: c++cbit-manipulation

解决方案


到达那里的步骤。

  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.

推荐阅读