我只想在特定位置向左移动一位,以保留其位置0,所以我不想使用<<运算符移动整个变量,这是一个示例:说该变量具有值1100 1010,我想移动第四位则结果应为1101 0010

最佳答案

到达那里的步骤。

  • 从原始编号中拉出位值。
  • 将位值左移一位。
  • 将位移后的值合并回原始数字。
  • // 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.
    

    09-10 05:16
    查看更多