是否有一种方法可以在c#中编写二进制文字,比如在十六进制前加上0x?0b不行。

如果不是,有什么简单的方法可以做到呢?某种字符串转换?


当前回答

c# 6.0和Visual Studio 2015中没有实现二进制文字特性。但在2016年3月30日,微软宣布了Visual Studio '15'预览的新版本,我们可以使用二进制文字。

我们可以使用一个或多个下划线(_)字符作为数字分隔符。所以代码片段看起来像这样:

int x           = 0b10___10_0__________________00; //binary value of 80
int SeventyFive = 0B100_________1011; //binary value of 75

WriteLine($" {x} \n {SeventyFive}");

我们可以使用0b和0b中的任何一个,如上面的代码片段所示。

如果你不想使用数字分隔符,你可以像下面的代码片段一样使用它而不使用数字分隔符

int x           = 0b1010000; //binary value of 80
int SeventyFive = 0B1001011; //binary value of 75

WriteLine($" {x} \n {SeventyFive}");

其他回答

你总是可以创建准字面量,包含你想要的值的常量:

const int b001 = 1;
const int b010 = 2;
const int b011 = 3;
// etc ...
Debug.Assert((b001 | b010) == b011);

如果你经常使用它们,那么你可以把它们包装在一个静态类中以供重用。

然而,稍微偏离主题,如果你有任何与位相关的语义(在编译时已知),我建议使用Enum代替:

enum Flags
{ 
    First = 0,
    Second = 1,
    Third = 2,
    SecondAndThird = 3
}
// later ...
Debug.Assert((Flags.Second | Flags.Third) == Flags.SecondAndThird);

虽然不可能使用文字,也许BitConverter也可以是一个解决方案?

如果你看一下。net编译器平台(“Roslyn”)的语言特性实现状态,你可以清楚地看到在c# 6.0中这是一个计划好的特性,所以在下一个版本中我们可以用通常的方式来实现它。

string sTable="static class BinaryTable\r\n{";
string stemp = "";
for (int i = 0; i < 256; i++)
{
stemp = System.Convert.ToString(i, 2);
while(stemp.Length<8) stemp = "0" + stemp;
sTable += "\tconst char nb" + stemp + "=" + i.ToString() + ";\r\n";
}
sTable += "}";
Clipboard.Clear();
Clipboard.SetText ( sTable);
MessageBox.Show(sTable);

使用这个,对于8位二进制,我用它来做一个静态类,它把它放入剪贴板。然后它被粘贴到项目中并添加到Using部分,因此任何与nb001010有关的内容都从表中取出,至少是静态的,但仍然…… 我使用c#进行大量的PIC图形编码,并在high - tech C中大量使用0b101010

——从代码输出的样本——

static class BinaryTable
{   const char nb00000000=0;
    const char nb00000001=1;
    const char nb00000010=2;
    const char nb00000011=3;
    const char nb00000100=4;
//etc, etc, etc, etc, etc, etc, etc, 
}

:-) 尼尔

c# 7.0支持二进制文字(以及可选的下划线分隔符)。

一个例子:

int myValue = 0b0010_0110_0000_0011;

您也可以在Roslyn GitHub页面上找到更多信息。