0

我想通过位掩码来跟踪一些选项,并从这个答案中借用位掩码值,但它们似乎不能一起工作。

#include <iostream>

#define OP1 0x00003FFFUL
#define OP2 0x00007FFFUL
#define OP3 0x0000FFFFUL

int main() {
        unsigned long params = 0; // .
        params |= OP3;
        if ( (params & OP1) == OP1)
                std::cout << "Whoa. Lame masking\n";
}

是类型问题,还是这种方法不能用于一次持有多个选项(OP1、OP2 和 OP3 都希望保持不变params)?

4

5 回答 5

4

For options you should use other masks, ones that are not overlapped, such as:

   #define OP1 0x000000FUL
   #define OP2 0x00000F0UL
   #define OP3 0x0000F00UL

or (in this case you'll be able to store as many options as available bits):

   #define OP1 0x0000001UL
   #define OP2 0x0000002UL
   #define OP3 0x0000004UL
   //ETC...

Your masks will never work properly because if OP3 is set then OP1 and OP2 will be contained (the same goes if you use OP2, then OP1 will be implied):

     FFFF = 1111111111111111
  &  3FFF = 0011111111111111
     -----------------------
     3FFF = 0011111111111111

The masks in the example you pasted were intended to extrapolate the last bits of an UL.

于 2011-06-05T20:33:53.320 回答
2

这个实现可能很奇怪,除非你有其他一些没有显示的东西(似乎不太可能,因为它取自另一个问题)。更好的解决方案可能是枚举您的位掩码。就像是:

enum values {
    aaa = 1 << 0,
    bbb = 1 << 1,
    ccc = 1 << 2,
    ab = aaa | bbb,
    ac = aaa | ccc,
    abc = aaa | bbb | ccc,
    bc = bbb | ccc, };

然后可以像这样使用:

unsigned int var = abc;
if (var & aaa) {
    cout << "OK";
}

输出“OK”

这为您提供了您可能想要的重叠值,同时还清楚地定义了它们之间的关系。如果你想变得更漂亮,你可以这样做:

namespace blah {
enum values {
    aaa = 1 << 0,
    bbb = 1 << 1,
    ccc = 1 << 2,
    ab = aaa | bbb,
    ac = aaa | ccc,
    abc = aaa | bbb | ccc,
    bc = bbb | ccc,
};
}

这将使您能够像这样使用它:

unsigned int var = blah::abc;
if (var & blah::aaa) {
    cout << "OK";
}

再次输出“OK”

如果您使用 uint 的完整宽度和标志的许多组合(它不会弄乱您的主命名空间),这会变得很好。

于 2011-06-05T20:50:52.240 回答
2

It has all 'options'. The problem is, bits in OP1, OP2 and OP3 overlap. OP3 has all bits of OP1 and OP2 also set. so, OP3&OP1 will equal OP1, and OP3&OP2 will equal OP2. Hence, the confusion. This wouldn't be the case if OP1=1, OP2=2, OP3=4. Then you'd also have to set the flag as

params |= OP1 | OP2 | OP3

But if you require OP1, OP2 and OP3 to be what you have provided, then there is no problem with your bitmasking code.

于 2011-06-05T20:28:21.697 回答
2

你认为 0xF 和 0x3 的值是多少?

于 2011-06-05T20:26:57.657 回答
1

您没有初始化参数。

尝试:

unsigned long params = 0;

于 2011-06-05T20:18:47.407 回答