saz*_*azr 1 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
}
Run Code Online (Sandbox Code Playgroud)
以下代码是否正确检查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
}
Run Code Online (Sandbox Code Playgroud)
不,不是,你应该使用按位AND运算符 - &并将标志设置为二进制值 - 你的直觉是正确的.
设置特定位的常用技巧是使用移位运算符:
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
Run Code Online (Sandbox Code Playgroud)
并检查int为
if (drawMethod & DRAW_REPEAT_X) //check it that particular flag is set, ignore others
{
}
Run Code Online (Sandbox Code Playgroud)
为此,您的标志变量每个都需要有一个唯一的位集.那一点是"旗帜".对于重要的按位表示的常量,使用十六进制或八进制(因为这些基数是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 */
Run Code Online (Sandbox Code Playgroud)
然后你使用按位&而不是逻辑 - 并&&测试位. a & b将只如果有是在这两个设置至少一个比特非零值,如果和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
}
Run Code Online (Sandbox Code Playgroud)
常量十六进制模式与一位集0x01,0x02,0x04,0x08,0x10,0x20,...