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

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


当前回答

虽然字符串解析解决方案是最流行的,但我不喜欢它,因为在某些情况下,解析字符串会极大地影响性能。

当需要一种位域或二进制掩码时,我宁愿这样写

long bitMask = 1011001;

后来

int bit5 = BitField。GetBit(位掩码,5);

Or

bool flag5 = BitField。GetFlag(位掩码,5);”

BitField类在哪里

public static class BitField
{
    public static int GetBit(int bitField, int index)
    {
        return (bitField / (int)Math.Pow(10, index)) % 10;
    }

    public static bool GetFlag(int bitField, int index)
    {
        return GetBit(bitField, index) == 1;
    }
}

其他回答

恐怕只有整数和十六进制直接(ECMA 334v4):

9.4.4.2整型字面值整型字面值用于写入值 类型为int、uint、long和ulong。 整数字面值有两种可能 形式:十进制和十六进制。

要解析,你可以使用:

int i = Convert.ToInt32("01101101", 2);

更新

c# 7.0现在有二进制字面值,这非常棒。

[Flags]
enum Days
{
    None = 0,
    Sunday    = 0b0000001,
    Monday    = 0b0000010,   // 2
    Tuesday   = 0b0000100,   // 4
    Wednesday = 0b0001000,   // 8
    Thursday  = 0b0010000,   // 16
    Friday    = 0b0100000,   // etc.
    Saturday  = 0b1000000,
    Weekend = Saturday | Sunday,
    Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}

最初的发布

由于主题似乎已经转向在枚举中声明基于位的标志值,因此我认为有必要指出这类事情的一个方便技巧。左移操作符(<<)将允许您将位推到特定的二进制位置。将其与根据同一类中的其他值声明枚举值的能力结合起来,您就拥有了非常易于阅读的位标志枚举声明性语法。

[Flags]
enum Days
{
    None        = 0,
    Sunday      = 1,
    Monday      = 1 << 1,   // 2
    Tuesday     = 1 << 2,   // 4
    Wednesday   = 1 << 3,   // 8
    Thursday    = 1 << 4,   // 16
    Friday      = 1 << 5,   // etc.
    Saturday    = 1 << 6,
    Weekend     = Saturday | Sunday,
    Weekdays    = Monday | Tuesday | Wednesday | Thursday | Friday
}
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, 
}

:-) 尼尔

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

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