jay - 7 months ago 65

C# Question

I ran into a bit of code similar to the code below and was just curious if someone could help me understand what it's doing?:

`int flag = 5;`

Console.WriteLine(0x0E & flag);

// 5 returns 4, 6 returns 4, 7 returns 6, 8 returns 8

Sandbox:

https://dotnetfiddle.net/NnLyvJ

Answer

This is the **bitwise AND** operator.
It performs an AND operation on the bits of a number.

A **logical** AND operation on two [boolean] values returns True if the two values are True; False otherwise.

A **bitwise** AND operation on two numbers returns a number from all the bits of the two numbers that are 1 (True) in both numbers.

Example:

```
5 = 101
4 = 100
AND = 100 = 4
```

Therefore, `5 & 4`

= 4.

This logic is heavily used for storing flags, you just need to assign each flag a power of 2 (1, 2, 4, 8, etc) so that each flag is stored in a different bit of the flags number, and then you just need to do `flags & FLAG_VALUE`

and if the flag is set, it'll return `FLAG_VALUE`

, otherwise `0`

.

C# provides a "cleaner" way to do this using `enum`

s and the `Flags`

attribute.

```
[Flags]
public enum MyFlags
{
Flag0 = 1 << 0, // using the bitwise shift operator to make it more readable
Flag1 = 1 << 1,
Flag2 = 1 << 2,
Flag3 = 1 << 3,
}
void a()
{
var flags = MyFlags.Flag0 | MyFlags.Flag1 | MyFlags.Flag3;
Console.WriteLine(Convert.ToString((int) flags, 2)); // prints the binary representation of flags, that is "1011" (in base 10 it's 11)
Console.WriteLine(flags); // as the enum has the Flags attribute, it prints "Flag0, Flag1, Flag3" instead of treating it as an invalid value and printing "11"
Console.WriteLine(flags.HasFlag(MyFlags.Flag1)); // the Flags attribute also provides the HasFlag function, which is syntactic sugar for doing "(flags & MyFlags.Flag1) != 0"
}
```

Excuse my bad english.