C++ 设置/取消设置单个位的简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3423788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple way to set/unset an individual bit
提问by djeidot
Right now I'm using this to set/unset individual bits in a byte:
现在我正在使用它来设置/取消设置一个字节中的各个位:
if (bit4Set)
nbyte |= (1 << 4);
else
nbyte &= ~(1 << 4);
But, can't you do that in a more simple/elegant way? Like setting or unsetting the bit in a single operation?
但是,您不能以更简单/优雅的方式做到这一点吗?喜欢在单个操作中设置或取消设置位?
Note: I understand I can just write a function to do that, I'm just wondering if I won't be reinventing the wheel.
注意:我知道我可以编写一个函数来做到这一点,我只是想知道我是否不会重新发明轮子。
采纳答案by Pascal Cuoq
Sure! It would be more obvious if you expanded the |=
and &=
in your code, but you can write:
当然!如果您在代码中扩展|=
和会更明显&=
,但您可以编写:
nbyte = (nbyte & ~(1<<4)) | (bit4Set<<4);
Note that bit4Set
must be zero or one—not any nonzero value— for this to work.
请注意,bit4Set
必须为零或一(不是任何非零值)才能使其工作。
回答by Nordic Mainframe
Put it in a function, the bool type will enforce 0,1 for all bitval inputs.
将它放在一个函数中,bool 类型将对所有 bitval 输入强制执行 0,1。
int change_bit(int val, int num, bool bitval)
{
return (val & ~(1<<num)) | (bitval << num);
}
回答by Alexandre C.
This is a perfectly sensible and completely standard idiom.
这是一个完全合理且完全标准的习语。
回答by Dan Moulding
Have you considered assigning mnemonics and/or identifiers to your bits, rather than referring to them by number?
您是否考虑过为您的位分配助记符和/或标识符,而不是通过数字来引用它们?
As an example, let's say setting bit 4 initiates a nuclear reactor SCRAM. Instead of referring to it as "bit 4" we'll call it INITIATE_SCRAM
. Here's how the code for this might look:
例如,假设设置位 4 启动核反应堆 SCRAM。我们将称其为 ,而不是将其称为“位 4” INITIATE_SCRAM
。以下是此代码的外观:
int const INITIATE_SCRAM = 0x10; // 1 << 4
...
if (initiateScram) {
nbyte |= INITIATE_SCRAM;
} else {
nbyte &= ~INITIATE_SCRAM;
}
This won't necessarily be any more efficient (after optimization) than your original code, but it's a little clearer, I think, and probably more maintainable.
这不一定比您的原始代码更有效(优化后),但我认为它更清晰一些,并且可能更易于维护。
回答by Mark B
This is tagged as C++ so have you considered using std::bitset
instead of doing all the bit manipulation yourself? Then you can just use array notation as: bits[3] = bit4Set
to set the appropriate bit.
这被标记为 C++ 所以你有没有考虑使用std::bitset
而不是自己做所有的位操作?然后你可以只使用数组表示法:bits[3] = bit4Set
设置适当的位。
回答by Donotalo
nbyte |= (1 << 4);
If the right hand side of the assignment, (1 << 4)
, is always a constant like this, then this would probably be optimized by compiler so it will be simpler in resulting assembly:
如果赋值的右侧(1 << 4)
, 始终是这样的常量,那么编译器可能会对其进行优化,因此生成的程序集会更简单:
mov r0, _nbyte
mov r1, 10H ; here is the optimization, no bit shift occured
or r0, r1
st _nbyte, r0