8

I am really stumped on this one. In C# there is a hexadecimal constants representation format as below :

int a = 0xAF2323F5;

is there a binary constants representation format?

Andrei Rînea
  • 19,592
  • 16
  • 117
  • 164

4 Answers4

9

Nope, no binary literals in C#. You can of course parse a string in binary format using Convert.ToInt32, but I don't think that would be a great solution.

int bin = Convert.ToInt32( "1010", 2 );
Ed S.
  • 119,398
  • 20
  • 176
  • 254
  • I'll leave the question open for a few hours but this being the first answer, if it proves true, it will be chosen as the official answer. Thank you. – Andrei Rînea Aug 07 '09 at 20:28
  • True, that works, and it is useful in most cases. Unfortunately it does not work if you're using it in a `switch(myVariable) { case bin: Console.WriteLine("value detected"); break; }` statement, since `case` only allows constants. – Matt Dec 19 '13 at 12:15
3

As of C#7 you can represent a binary literal value in code:

private static void BinaryLiteralsFeature()
{
    var employeeNumber = 0b00100010; //binary equivalent of whole number 34. Underlying data type defaults to System.Int32
    Console.WriteLine(employeeNumber); //prints 34 on console.
    long empNumberWithLongBackingType = 0b00100010; //here backing data type is long (System.Int64)
    Console.WriteLine(empNumberWithLongBackingType); //prints 34 on console.
    int employeeNumber_WithCapitalPrefix = 0B00100010; //0b and 0B prefixes are equivalent.
    Console.WriteLine(employeeNumber_WithCapitalPrefix); //prints 34 on console.
}

Further information can be found here.

Luis Teijon
  • 4,433
  • 6
  • 33
  • 56
2

You could use an extension method:

public static int ToBinary(this string binary)
{
    return Convert.ToInt32( binary, 2 );
}

However, whether this is wise I'll leave up to you (given the fact it will operate on any string).

Dan Diplo
  • 24,785
  • 4
  • 64
  • 87
0

Since Visual Studio 2017, binary literals like 0b00001 are supported.

Andreas
  • 5,050
  • 8
  • 42
  • 51
Xiaoyuvax
  • 51
  • 6
  • 1
    Is this a repeat of [this existing answer](https://stackoverflow.com/a/41193863)? – Pang Aug 02 '17 at 06:47
  • sorry, but i want to figure out that the newly released VS 2017 supports such a usage,hope this helps. – Xiaoyuvax Aug 17 '17 at 05:17
  • I don't see how repeating something that was already explained much better in the accepted answer could ever help anyone. – Nyerguds Mar 21 '18 at 11:48