How to assign a value to an Enum with binary notation?

Asked

Viewed 1,531 times

9

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

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: 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 declare directly each value

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

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
}
  • It was something like this that I was looking for. I think it’s much better to say that Down is "3 bit discolored" than simply the magic number 8. Obrg.

  • 1

    And for those who think this is inefficient: compiler optimization solves this question.

10

4

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

int binario = Convert.ToInt32("0100", 2);

0

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

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

Example of use: link

Being that 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 it out? Just open the browser developer tool (usually F12) and paste the values.

  • It just doesn’t make the slightest difference to use hexadecimal or decimal, it only matters for the syntax. And what you wanted is binary.

  • Yes, exactly, so much so that the right answer is still the one that uses the operator <<. I just put this answer to complement and enrich the post same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.