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
  • 20,288
  • 17
  • 117
  • 166

4 Answers4

8

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.
  • 122,712
  • 22
  • 185
  • 265
  • 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
  • 1
    It's possible now as `0b1010` as of C# 7 (more than 5 years ago as of this comment.) See answer by @Luis – Mike Jun 13 '22 at 12:29
4

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,769
  • 7
  • 36
  • 57
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
  • 25,076
  • 4
  • 67
  • 89
0

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

Andreas
  • 5,393
  • 9
  • 44
  • 53
Xiaoyuvax
  • 71
  • 6
  • 2
    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