bit-level logic operations on enums

Era Scarecrow rtcvb32 at yahoo.com
Fri Mar 1 05:41:26 PST 2013


On Friday, 1 March 2013 at 12:57:14 UTC, d coder wrote:
> Greetings
>
> Currently DMD allows me to bit-or two enum variables, but not 
> bit-and. For example in the following code, DMD is OK with line 
> 6, but gives an error for line 9. I do not see any logic why 
> DMD does that. Is it a bug or is it intended.
>
> BTW if I declare all a,b,c and d as "enum BING_e", then DMD 
> gives errors for both line 6 and 9.
>
> enum BING_e: byte {NONE_BING = 0b00, FOO_BING = 0b01, // 1
>     BAR_BING = 0b10, BOTH_BING = 0b11}                // 2
> void main() {                                         // 3
>   BING_e a = BING_e.FOO_BING;                         // 4
>   BING_e b = BING_e.BAR_BING;                         // 5
>   BING_e c = a | b;                                   // 6
>   import std.stdio;                                   // 7
>   writeln(c);                                         // 8
>   BING_e d = a & b;                                   // 9
>   import std.stdio;                                   // 10
>   writeln(d);                                         // 11
> }                                                     // 12

  To do the binary operators it converts the flags to numbers, 
however you have to cast it for it to become a enum again, 
however this is unsafe as you could accidentally hold a value 
that has no name;

   //with your code
   BING_e c = cast(BING_e) (a | 0x10); //suppose to be 0b10

  If you want to work with flags I have a implementation that I 
think is very good and simple.

  Note: If you have a flag that covers multiple bits like 
BOTH_BING, it must match ALL the bits to qualify.

  https://github.com/rtcvb32/Side-Projects/blob/master/flags.d


More information about the Digitalmars-d mailing list