2009-08-07 70 views
8

我真的很難過這個。在C#中有一個十六進制常量表示格式,如下所示:C#二進制常量表示

int a = 0xAF2323F5; 

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

+0

你是什麼意思? const int a = 2938315765; – Paco 2009-08-07 20:28:31

+1

謝謝,我想你的結果是正確的,但我正在尋找系統的解決方案。我應該爲每個需要轉換的二進制常量發佈一個問題stackoverflow? – 2009-08-07 20:29:11

+0

..例如10110011 – 2009-08-07 20:29:46

回答

3

作爲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. 
} 

的進一步信息可以發現here

9

不,在C#中沒有二進制文字。你當然可以使用Convert.ToInt32解析二進制格式的字符串,但我認爲這不是一個好的解決方案。

int bin = Convert.ToInt32("1010", 2); 
+0

我會讓問題在幾個小時內公開,但這是第一個答案,如果它是真實的,它將被選爲官方答案。謝謝。 – 2009-08-07 20:28:06

+2

這是真的......現在不妨接受。 – 2009-08-07 20:30:01

+0

的確如此,這是有效的,並且在大多數情況下它很有用。不幸的是,如果你在'switch(myVariable){case bin:Console.WriteLine(「value detected」)中使用它,打破; }'語句,因爲'case'只允許常量。 – Matt 2013-12-19 12:15:26

2

可以使用擴展方法:

public static int ToBinary(this string binary) 
{ 
    return Convert.ToInt32(binary, 2); 
} 

然而,這是否是明智的,我會離開給你(因爲事實上它可以在任何字符串操作)。

0

由於Visual Studio 2017支持二進制文字(如0b00001)。

+0

這是[現有的答案](https://stackoverflow.com/a/41193863)的重複嗎? – Pang 2017-08-02 06:47:22

+0

對不起,但我想知道新發布的VS 2017支持這種用法,希望這有助於。 – Xiaoyuvax 2017-08-17 05:17:18