c++ - 检查标志是否设置在整数变量中

标签 c++ c bit-manipulation

我正在制作我自己的简单绘图引擎。我正在尝试使用我认为称为按位比较的方法来确定变量是否已设置为特定值,但我可能错了。

我一直对以下是什么以及如何使用它感到困惑:

int DRAW_REPEAT_X = 70001; // I have a feeling I should make this value binary instead of a unique number, ie, 0
int DRAW_REPEAT_Y = 70002; // I have a feeling I should make this value binary instead of a unique number, ie, 2
int drawMethod    = DRAW_REPEAT_X | DRAW_REPEAT_Y; // this means I want to repeat an image on both the x and y axis doesn't it?

// Now I want to check if drawMethod has DRAW_REPEAT_X set: this is where I struggle to know how to check this
// Is the following correct?
if (drawMethod && DRAW_REPEAT_X) {
  // the user wants me to repeat an image along the x axis
}

// Now I want to check if drawMethod has DRAW_REPEAT_Y set: this is where I struggle to know how to check this
if (drawMethod && DRAW_REPEAT_Y) {
  // the user wants me to repeat an image along the x axis
}

以下代码是否正确检查是否设置了 DRAW_REPEAT_X?在我的安定检查中它总是返回 1。

编辑 并检查这两个位是否都已设置,我应该这样做吗?

if (drawMethod & DRAW_REPEAT_X & DRAW_REPEAT_Y) {
   // both set
}

// OR

if (drawMethod & DRAW_REPEAT_X && drawMethod & DRAW_REPEAT_Y) {
   // both set
}

最佳答案

为此,您的每个标志变量都需要设置一个唯一的位。那一点就是“旗帜”。对于重要的按位表示的常量,使用十六进制或八进制(因为这些基数是 2 的幂)比十进制更方便。所以,例如:

enum {
    DRAW_REPEAT_X = 0x01,    /* First bit set */
    DRAW_REPEAT_Y = 0x02,    /* Second bit set */
    DRAW_MIRRORED = 0x04,    /* Third bit set */
};

int drawMethod = DRAW_REPEAT_X | DRAW_REPEAT_Y;  /* Will have both first and second bits set */

然后您使用按位与 & 而不是逻辑与 && 来测试位。当且仅当在 ab 中都设置了至少一位时,a & b 才会为非零。在测试标志的情况下,其中一个将只设置一位 - 您感兴趣的标志 - 因此 a & flag 的结果将非零当且仅当标志设置在 a 中:

if (drawMethod & DRAW_REPEAT_X) {
  // the user wants me to repeat an image along the x axis
}

if (drawMethod & DRAW_REPEAT_Y) {
  // the user wants me to repeat an image along the x axis
}

设置一位常量的十六进制模式是0x010x020x040x080x10, 0x20, ...

关于c++ - 检查标志是否设置在整数变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13464063/

相关文章:

C++ 绑定(bind)返回类型模板参数

c++ - C 中优雅的二进制 i/o?

c++ - 如何快速比较 C++ 中的可变长度位串?

java - 如何设置java Short中的最高位?

c++ - 为什么在 sync_with_stdio(false) 之前使用 cin 给下一个 i/p 变量随机值

c++ - 运算符重载逻辑问题

c - 通过 fscanf() 读取的值未打印出来

excel - 将 Excel 按位函数(BITAND 或 BITOR)应用于具有较大值的范围

c++ - 您多久检查一次 C++ 新指令中的异常?

c - 使用 int 数组作为 switch case