在c++中不改变倒数第二位的情况下移动整数中的位
Shifting bits in an integer without changing the penultimate bit in C++?
假设我有一个32位整数:
000001010100010000100010001001 1 0
(倒数第二位为粗体/斜体)
如果向右移动2个单位,就会得到
00000001010100010000100010001001
现在倒数第二个位丢失了。我想存储原始值,然后使用||(逻辑或),但这只会在倒数第二个位被设置为1时起作用。如果是0呢?
您需要按位,而不是逻辑或;为了保留这个值,你需要在插入旧值之前清除新值中的位:
uint32_t const shift = 2; // number of bits to shift by
uint32_t const mask = (1 << 1); // set of bits to preserve
uint32_t bit_to_save = value & mask;
value >>= shift;
value &= ~mask;
value |= bit_to_save;
或者,如果你喜欢简洁的话:
value = ((value >> shift) & ~mask) | (value & mask);
使用按位运算:
(x>>2) & ~2 | (x&2)
x>>2
右移2。
& ~2
置倒数第二位为0
| (x&2)
'接枝'在原编号倒数第二位
int x;//whatever
int penultimate_shift=(x&0x2)|((x>>2)&~0x2);
相关文章:
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 如何在不复制的情况下将一个向量移动到另一个向量中
- C++ 移动语义是否在任何情况下都能节省资源?
- 如何在没有 std::move 的情况下移动临时对象
- 为什么C++默认情况下不移动构造右值引用?
- 为什么在这种情况下调用非常量右值移动构造函数?
- 在不中断引用的情况下移动静态库的 *.pdb 文件 - LNK4099
- QT QTest::键单击或鼠标移动似乎不适用于 QMenu 在我的情况下
- 如何在不妨碍RVO的情况下确保移动?
- 无法在不移动的情况下从函数返回 std::unique_ptr
- 默认情况下,返回是否使用移动或复制语义
- 在这种情况下,值是否会移动
- 为什么在这种情况下不调用我的移动构造函数?(首先分配 r 值引用并创建对象)
- 如果在没有move构造函数的情况下移动对象,会发生什么
- 在不影响其他对象的情况下移动对象(使用opengl)
- 默认/删除在存在RVO的情况下移动构造函数和赋值
- 对容器进行排序,然后在保留原始排序的情况下移动元素
- 在c++中不改变倒数第二位的情况下移动整数中的位
- 从技术上讲,如何在不复制的情况下移动函数返回值
- 如何在不移动整个场景的情况下移动一个2d对象?