int sampleVariable; // declared and initialized and used elsewhere
if (sampleVariable & 2)
someCodeIwantExecuted();
因此,如果我想手动操作 sampleVariable,以便 if 语句评估为 true 并执行 someCodeIwantExecuted(),我会执行以下操作吗?
sampleVariable |= (1 << 1);
请记住,我不知道 sampleVariable 的值是多少,我想保持其余位相同。只需更改位,以便 if 语句始终为真。
最佳答案
解决方案相当直接。
// OP suggestion works OK
sampleVariable |= (1 << 1);
// @Adam Liss rightly suggests since OP uses 2 in test, use 2 here.
sampleVariable |= 2
// My recommendation: avoid naked Magic Numbers
#define ExecuteMask (2u)
sampleVariable |= ExecuteMask;
...
if (sampleVariable & ExecuteMask)
注意:当使用 (1 << 1)
中的 shift 样式时, 确保 1
的类型匹配您的目标类型
unsigned long long x;
x |= 1 << 60; // May not work if `sizeof(int)` < `sizeof(x)`.
x |= 1ull << 60;
进一步:考虑unsigned
的优点类型。
// Assume sizeof int/unsigned is 4.
int i;
y |= 1 << 31; // Not well defined
unsigned u;
u |= 1u << 31; // Well defined in C.
关于c - 基本 C 位运算示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19529902/