设置/取消设置单个位的简单方法
现在我用它来设置/取消设置一个字节中的各个位:
if (bit4Set)
nbyte |= (1 << 4);
else
nbyte &= ~(1 << 4);
但是,你不能以更简单/优雅的方式做到这一点吗?喜欢在一次操作中设置或取消设置该位吗?
注意:我知道我可以编写一个函数来做到这一点,我只是想知道我是否不会重新发明轮子。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当然!如果在代码中扩展
|=
和&=
会更明显,但你可以这样写:注意
bit4Set
必须是零或一(不是任何非零值)才能起作用。Sure! It would be more obvious if you expanded the
|=
and&=
in your code, but you can write:Note that
bit4Set
must be zero or one —not any nonzero value— for this to work.将其放入函数中,bool 类型将为所有 bitval 输入强制执行 0,1。
Put it in a function, the bool type will enforce 0,1 for all bitval inputs.
这是一个非常明智且完全标准的习语。
This is a perfectly sensible and completely standard idiom.
您是否考虑过为您的位分配助记符和/或标识符,而不是通过数字引用它们?
举个例子,假设设置位 4 启动核反应堆 SCRAM。我们不将其称为“位 4”,而是将其称为
INITIATE_SCRAM
。其代码可能如下所示:这不一定比原始代码更有效(优化后),但我认为它更清晰,并且可能更易于维护。
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: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.
如果赋值的右侧
(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:它被标记为 C++,所以您是否考虑过使用 std::bitset 而不是自己进行所有位操作?然后您可以使用数组表示法:bits[3] = bit4Set 来设置适当的位。
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.