Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#二进制常数表示法_C#_Binary_Format_Constants_Representation - Fatal编程技术网

C#二进制常数表示法

C#二进制常数表示法,c#,binary,format,constants,representation,C#,Binary,Format,Constants,Representation,我真的被这件事难住了。在C#中,十六进制常数表示格式如下: int a = 0xAF2323F5; 有二进制常量表示格式吗?没有,C#中没有二进制文本。当然,您可以使用Convert.ToInt32解析二进制格式的字符串,但我认为这不是一个很好的解决方案 int bin = Convert.ToInt32( "1010", 2 ); 您可以使用扩展方法: public static int ToBinary(this string binary) { return Convert.T

我真的被这件事难住了。在C#中,十六进制常数表示格式如下:

int a = 0xAF2323F5;

有二进制常量表示格式吗?

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

int bin = Convert.ToInt32( "1010", 2 );
您可以使用扩展方法:

public static int ToBinary(this string binary)
{
    return Convert.ToInt32( binary, 2 );
}
然而,这是否明智,我将留给您(考虑到它将对任何字符串进行操作的事实)。

从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.
}

可以找到更多信息。

自Visual Studio 2017以来,支持0b00001之类的二进制文字。

我将把这个问题保留几个小时,但这是第一个答案,如果它被证明是真的,它将被选为正式答案。谢谢。没错,这很有效,而且在大多数情况下都很有用。不幸的是,如果您在
开关(myVariable){case-bin:Console.WriteLine(“value-detected”);break;}
语句中使用它,它将不起作用,因为
case
只允许常量。这是什么意思?常数INTA=2938315765;谢谢,我想你的结果是正确的,但我一直在寻找系统的解决方案。我应该为我需要转换的每个二进制常量发布一个问题o stackoverflow吗?这是一个很好的指针,我不知道搜索“literal”,尽管我应该这样做。也许Jeff说的搜索算法有点糟糕(39%?)是对的。我在链接的帖子中发布了我的答案。这是重复的吗?对不起,但我想知道新发布的VS 2017支持这种用法,希望这能有所帮助。我不认为重复已经在公认的答案中解释得更好的东西对任何人都有帮助。