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#
We can check if two given values are equal or not by making use of the XOR operator. If two numbers are equal, then their bitwise XOR will always result in 0. Therefore, a = b.
Bitwise AND Operator & The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. In C Programming, the bitwise AND operator is denoted by & .
The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it. When bitwise operator is applied on bits then, all the 1's become 0's and vice versa. The operator for the bitwise complement is ~ (Tilde).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With