基本C按位运算示例

时间:2013-10-22 23:05:52

标签: c bit-manipulation

int sampleVariable; // declared and initialized and used elsewhere

if (sampleVariable & 2)
     someCodeIwantExecuted();

因此,如果我想手动操作sampleVariable,以便if语句评估为true而someCodeIwantExecuted()执行,我会执行以下操作?

sampleVariable |= (1 << 1);

请记住,我不知道sampleVariable的值是什么,我想保持其余的位相同。只需更改位,以便if语句始终为真。

1 个答案:

答案 0 :(得分:0)

解决方案相当直接。

//  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)中使用班次样式时,请确保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.