检查标志是否在整数变量中设置 [英] Check if flag is set in integer variable

查看:66
本文介绍了检查标志是否在整数变量中设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making my own simple drawing engine. I am trying to determine if a variable has been set to a specific value using what I think is called bitwise comparison but I maybe wrong.

我一直对以下内容及其用法感到困惑:

I've always been a bit confused about what the following is and how I use it:

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.

Is the following code correctly checking if DRAW_REPEAT_X is set? It always returns 1 in my anding check.

编辑 并检查两个位是否都设置了吗?

EDIT And to check whether both bits are set do I do this?

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

// OR

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

推荐答案

不是,您应该使用按位AND运算符-&并将标志设置为二进制值-您的直觉在那一侧是正确的

No it isn't, you should use the bitwise AND operator instead - & and set the flags as binary values - your intuition is correct on that side.

设置特定位的常见技巧是使用移位运算符:

A common trick to setting specific bits is using the shift operator:

int DRAW_REPEAT_X = 0x1 << 0;  //first bit set to 1, others 0
int DRAW_REPEAT_Y = 0x1 << 1;  //second bit set to 1, others 0

并检查int为

if (drawMethod & DRAW_REPEAT_X)  //check it that particular flag is set, ignore others
{
}

这篇关于检查标志是否在整数变量中设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆