0

I have the following code:

    private enum Wall
    {
        Up = 0x0001,
        Down = 0x0010,
        Left = 0x0100,
        Right = 0x1000,
    }

private void Test()
{
    int walls = 0x1111;
    var wallsWithRightWallRemoved = walls | Wall.Right;
    // wallsWithRightWallRemoved  should now be this: 0x0111    
}

I have a variable called walls where the 0x1111 represents 4 booleans basically. From the walls I want to remove the right wall so I substract it from it (walls | Wall.Right;) , but I am getting "Cannot apply operator & to operands of type int". Basically I want to end up with a variable which contains 0x0111.

Thank you

Askerman
  • 787
  • 1
  • 12
  • 31
  • 1
    `|` is bit-wise OR, not subtraction. You're *adding* the right wall, not removing it. – Luaan Jul 31 '16 at 17:36
  • I think part of your error is your enum is missing `[Flags]` – Scott Chamberlain Jul 31 '16 at 17:37
  • @Scott [`[Flags]` doesn't alter an enum's implementation, it's for display purposes only](http://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c). :) – CodeCaster Jul 31 '16 at 17:38
  • 1
    @Askerman _"a strange int related error"_ isn't answerable. Please read [ask] and provide a [mcve]. – CodeCaster Jul 31 '16 at 17:39
  • Thanks, but it still says "Cannot apply operator & to operands of type int" even with Flags added – Askerman Jul 31 '16 at 17:40
  • `walls & (int) ~ Wall.Right` – Charles Mager Jul 31 '16 at 17:40
  • What is the ~ for? But why do it need to cast it when the enum is already an int? – Askerman Jul 31 '16 at 17:42
  • 1
    @Askerman it can be *cast* to an `int`, but it isn't an `int`. `int right = Wall.Right` wouldn't compile, for example; you need to cast it. `~` is the bitwise complement operator, it flips the bits so you're AND-ing `0111` which will unset the fourth bit. – Charles Mager Jul 31 '16 at 17:48
  • You're looking for the logical XNOR operation, also knows as logical biconditional. It's achieved in C# as follows: `wallsWithRightWallRemoved = ~(walls ^ Wall.Right)` Also you would need to use the `[Flags] ` attribute on your enum. – silkfire Jul 31 '16 at 17:52

1 Answers1

0
wallsWithRightWallRemoved = walls & 0x0111;

Or will set bits that are in either. And will unset bits that are 0 in either, which is what you want to do.

wizzardmr42
  • 1,634
  • 12
  • 22