boop
boop

Reputation: 7788

Translating bitwise comparison from C++ to C#

I've the given condition from a cpp source.

if (!(faces & activeFace) || [...]) { ... }

I want to translate this into C#.

When I understand this right, this means as much as if activeFace is *not* in faces then... - not?

So what would be the equivalent in C#?
Note: I can't use faces.HasFlag(activeFace)

Well it should be

if ((faces & activeFace) == 0 || [...]) { ... }

Am I right?

For the completeness here the actual Flag enum

[Flags]
enum Face {
    North = 1,
    East = 2,
    South = 4,
    West = 8,
    Top = 16,
    Bottom = 32
};

Well It's the same in cpp, you just need to add a [Flags] attribute in C#

Upvotes: 9

Views: 214

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112279

I would add a value None = 0 to the enum

[Flags]
enum Face {
    None = 0,
    North = 1,
    East = 2,
    South = 4,
    West = 8,
    Top = 16,
    Bottom = 32
};

and then test

if ((faces & activeFace) == Face.None || otherExpr) {
    ...
}

A good reason to add a 0 constant to an enum is that class fields are zeroed by default and omitting a 0 constant would lead to enum values not corresponding to any enum constant. It is legal in C# to do that, but it's not a good practice. C# does not test whether values assigned to enums are valid enum constants.

But if you cannot change the enum, you can cast the enum value to int

if ((int)(faces & activeFace) == 0 || otherExpr) {
    ...
}

And yes, in C++ any int unequal 0 is considered as Boolean true value, so !(faces & activeFace) in C++ means: activeFace is not in faces

Upvotes: 5

Related Questions