Translating bitwise comparison from C++ to C#
Asked Answered
L

1

9

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#

Lynden answered 4/8, 2014 at 19:40 Comment(9)
Removed your awkward line. Not relevant and imho the question is not awkward but something good to know for beginnersAlaniz
What data types are faces and activeFace?Weever
Am I right? Yes. Question solved?Fossilize
this is fairly easy to test. Did you try anything prior to asking?Cartridge
You don't actually have to add the [Flags] attribute in C#. Your code will work just fine without it.Fossilize
@Default I've never used cpp. And on windows it's not as easy as apt-get install gcc ; gcc test.cpp (or whatever the actual command would be) - so: no.Lynden
@Brettetete FYI, there are online compilers to easily test code, for instance ideone.com or dotnetfiddle.net.Cartridge
@Jashaszun: It is a good practice in C# to add a FlagsAttribute when the enum is used as flag, i.e. if its constants are powers of 2, as this expresses the intention of the programmer. The attribute also influences the way ToString works and produces a neat output if flags are combined. This is useful when debugging.Cuculiform
@OlivierJacot-Descombes Oh wow! I've been programming in C# for years and I didn't know that [Flags] changed ToString()! I guess you learn something new every day.Fossilize
C
5

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

Cuculiform answered 4/8, 2014 at 19:52 Comment(1)
Well, it seems you put all the other answers out of contention. Thanks for your extensive answer, here your well deserved +1 ;)Lynden

© 2022 - 2024 — McMap. All rights reserved.