开发者

How do |= and &= work?

I want to make an enum in such a way that I can & parameters after |ing them in.

Can I simply do:

enum Things
{
   Something,
SomethingElse
};

Or must I be careful to give them specific numbers for this to work开发者_如何学Python?

Also if a value, like say, 3, has already been |='d in, would |= it in again cause this to malfunction (as in, if(attributes & 3) would no longer work)

Thanks


Then define your enum as:

enum Things
{
   Something = 1       //0000 0001
   SomethingElse = 2;  //0000 0010
   SomethingX = 4;     //0000 0100
   SomethingY = 8;     //0000 1000
   SomethingZ = 16;    //0001 0000
};

The idea is, only one bit in the binary representation should be 1, others should be 0, as shown in the comments above. Also, I used 8 bits only in the comment, that doesn't mean that the enum values are one byte size. I only used them for convenience. Enum values can be very large, can hold even long.


You have to use special values, namely powers of two (1, 2, 4, 8, 16, ...). And you should probably read this before investigating this "| and & feature" any further: http://en.wikipedia.org/wiki/Binary_numeral_system

This might also be worth reading: http://en.wikipedia.org/wiki/Flag_(computing)


Packing flags with | and & works best when you take advantage of the computer's native binary encoding.

So, using the powers of 2 (here in decimal representation):

enum Things
{
   Something     = 1,
   SomethingElse = 2,
   SomethingMore = 4,
   SomethingHuge = 8
};

This enables each flag to be represented exclusively in a single bit of an integer, allowing each one to be activated and de-activated individually.

The result is:

char x = 0;
x |=  Something;     // x in binary looks like 00000001
x |=  SomethingMore; // x in binary looks like 00001001
x &= ~Something;     // x in binary looks like 00001000

I hope that this makes sense.


If you want to use bit-wise operations with an Enum, the values must be a power of 2. This is commonly referred to as a Bit Field.


As Nawaz said and you can make it easier if you use a hexadecimal codes

enum Things
{
   Something =     0x00000001   //0000 0001
   SomethingElse = 0x00000002;  //0000 0010
   SomethingX    = 0x00000004;  //0000 0100
   SomethingY    = 0x00000008;  //0000 1000
   SomethingZ    = 0x00000010;  //0001 0000 // instead of 16
   SomethingZ2   = 0x00000020;  //0010 0000 // instead of 32
   SomethingZ3   = 0x00000040;  //0100 0000 // instead of 64
   SomethingZ4   = 0x00000080;  //1000 0000 // instead of 128
};

Or even better use a macro:

#define BITMASK(x) (1<<(x))

enum Things
{
   Something =    BITMASK(0)   //0000 0001
   SomethingElse = BITMASK(1) ;  //0000 0010
   SomethingX    = BITMASK(2) ;  //0000 0100
   SomethingY    = BITMASK(3) ;  //0000 1000
   SomethingZ    = BITMASK(4) ;  //0001 0000 
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜