【发布时间】:2012-06-23 15:35:29
【问题描述】:
我用这种方式按位打开和关闭位:
unsigned char myChar = ...some value
myChar |= 0x01 << N // turn on the N-th bit
myChar &= ~(0x01 << N) //turn off the N-th bit
现在,假设 N 的值是已知的,但设置/取消设置操作取决于另一个无符号字符的位的值。 从现在开始,我就是这样做的:
if ((otherChar & (0x01 << M)) != 0)
{
//M-th bit of otherChar is 1
myChar |= 0x01 << N;
}else
{
myChar &= ~(0x01 << N);
}
这应该是一种从无符号字符到另一个字符的“移动位”操作。
我的问题: 有没有办法在不使用条件的情况下做到这一点? (也没有 std::bitset)
【问题讨论】:
-
当你说
N-th bit时,是不是从零开始计数? -
是..从零开始。这相关吗?
标签: c++ c bit-manipulation