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

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


当前回答

如果你看一下。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, 
}

:-) 尼尔

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

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

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

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

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

在@StriplingWarrior关于枚举中的位标志的回答中,有一个简单的约定,你可以在十六进制中使用,通过位移位向上计数。使用序列1-2-3 -8,向左移动一列,重复。

[Flags]
enum Scenery
{
  Trees   = 0x001, // 000000000001
  Grass   = 0x002, // 000000000010
  Flowers = 0x004, // 000000000100
  Cactus  = 0x008, // 000000001000
  Birds   = 0x010, // 000000010000
  Bushes  = 0x020, // 000000100000
  Shrubs  = 0x040, // 000001000000
  Trails  = 0x080, // 000010000000
  Ferns   = 0x100, // 000100000000
  Rocks   = 0x200, // 001000000000
  Animals = 0x400, // 010000000000
  Moss    = 0x800, // 100000000000
}

从右栏开始向下扫描,注意1-2-4-8 (shift) 1-2-4-8 (shift)…


为了回答最初的问题,我赞同@Sahuagin的建议,使用十六进制字面量。如果您经常使用二进制数,以至于这成为一个问题,那么值得您花点时间来掌握十六进制的诀窍。

如果您需要在源代码中看到二进制数字,我建议像上面那样添加带有二进制文字的注释。

基本上,我认为答案是否定的,没有简单的方法。使用十进制或十六进制常量——它们简单明了。@RoyTinkers的回答也很好-使用评论。

int someHexFlag = 0x010; // 000000010000
int someDecFlag = 8;     // 000000001000

这里的其他答案提供了几个有用的工作回合,但我认为它们并不比简单的答案更好。c#语言设计人员可能认为'0b'前缀是不必要的。HEX很容易转换为二进制,而且大多数程序员都必须知道0-8的DEC等价值。

此外,在调试器中检查值时,它们将显示为HEX或DEC。