How do I assign a value to an enum with binary notation?

8

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 0 :

var numeroOct = 037;

But how do you declare binary numbers?

var numeroBin = ??00101

I'm going to use this to improve the calculations with bitwise operators, my intention is to avoid commenting on 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 instead declare each value directly

public enum Direction
{
    None = ??0000
    Left = ??0001
    Right = ??0010
    Up = ??0100
    Down = ??1000
}
    
asked by anonymous 23.04.2014 / 15:53

4 answers

11

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

public enum Direction
{
    None = 0,      //0000
    Left = 1,      //0001
    Right = 1<<1,  //0010
    Up = 1<<2,     //0100
    Down = 1<<3,   //1000
}
    
23.04.2014 / 16:35
10

The C # 7 has syntax for native binary representation . You can use:

int x = 0b0111_0100;

You can even use tabs for easy reading. The separators can be used in the other numeric representations as well.

Font .

I placed it in Github for future reference .

    
23.04.2014 / 17:11
4

Unable to declare binary literals in C# . What you can do is parse a string for the binary format using Convert.ToInt32 , as can be seen here and here .

int binario = Convert.ToInt32("0100", 2);
    
23.04.2014 / 16:27
0

Working a little with DLLImport for Microsoft assemblies, I noticed that they use a very efficient [Flag] notation, simply using hexadecimal values:

public enum Direction
{
    None = 0x1,   //1
    Left = 0x2,   //2
    Right = 0x4,  //4
    Up = 0x8,     //8
    Down = 0x10,   //16
}

Example Usage: link

Since the number 0x10 represents 16 , and so on, it is possible to continue the numbering:

0x20 == 32
0x40 == 64
0x80 == 128
0x100 == 256
0x200 == 512
0x400 == 1024
0x800 == 2048
0x1000 == 4096
...

Want to check out? Just open the browser's developer tool (usually F12 ) and paste the values.

    
13.11.2015 / 13:46