C#二进制常量表示

And*_*nea 8 c# format binary constants representation

我真的很难过这个.在C#中有一个十六进制常量表示格式如下:

int a = 0xAF2323F5;
Run Code Online (Sandbox Code Playgroud)

是否有二进制常量表示格式?

Ed *_* S. 9

不,C#中没有二进制文字.您当然可以使用Convert.ToInt32以二进制格式解析字符串,但我认为这不是一个很好的解决方案.

int bin = Convert.ToInt32( "1010", 2 );
Run Code Online (Sandbox Code Playgroud)


Lui*_*jon 5

从 C#7 开始,您可以在代码中表示二进制文字值:

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.
}
Run Code Online (Sandbox Code Playgroud)

更多信息可以在这里找到。