c - 基本 C 位运算示例

标签 c bit-manipulation

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/

相关文章:

c - 截断文件时出现段错误

c++ - 条件下的按位操作设置变量

matlab - eps() 在 MATLAB 中是如何计算的?

algorithm - 找到二进制数1的索引,即2的幂

c - 什么是 12345 >> 2 真的在做算术?

c - 我是否需要释放一个从函数接收动态分配对象的指针?

c - 为什么减去字符实现的行为是特定的?

c++ - C++ 中的复杂矩阵指数

c - bit twiddling 是对嵌入式工程师的一个很好的考验

c - 使用 gcc 版本 4.3.3 构建 OpenSSL 1.1.1c 时出现问题