Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top