Andrei Rînea
Andrei Rînea

Reputation: 20800

C# binary constants representation

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?

Upvotes: 8

Views: 12253

Answers (4)

Xiaoyuvax
Xiaoyuvax

Reputation: 71

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

Upvotes: 0

Luis Teijon
Luis Teijon

Reputation: 4909

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.

Upvotes: 5

Ed Swangren
Ed Swangren

Reputation: 124790

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 );

Upvotes: 8

Dan Diplo
Dan Diplo

Reputation: 25359

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).

Upvotes: 2

Related Questions