c# – How to assign a value to an enum with binary notation?

Question:

To work with hexadecimal numbers, just add 0x in front of the number, like this:

var numeroHexa = 0xff1120;

The same goes for octal numbers, adding the 0 :

var numeroOct = 037;

But how do you declare binary numbers?

var numeroBin = ??00101

I will use this to improve calculations with bitwise operators, my intention is: to avoid commenting the binary value of each enum:

public enum Direction
{
    None = 0,   //0000
    Left = 1,   //0001
    Right = 2,  //0010
    Up = 4,     //0100
    Down = 8,   //1000
}

And yes directly declare each value

public enum Direction
{
    None = ??0000
    Left = ??0001
    Right = ??0010
    Up = ??0100
    Down = ??1000
}

Answer:

Considering NULL's answer about the lack of literal binaries, I suggest using the following to improve the readability of the enum :

public enum Direction
{
    None = 0,      //0000
    Left = 1,      //0001
    Right = 1<<1,  //0010
    Up = 1<<2,     //0100
    Down = 1<<3,   //1000
}
Scroll to Top