是否有一种方法可以在c#中编写二进制文字,比如在十六进制前加上0x?0b不行。
如果不是,有什么简单的方法可以做到呢?某种字符串转换?
是否有一种方法可以在c#中编写二进制文字,比如在十六进制前加上0x?0b不行。
如果不是,有什么简单的方法可以做到呢?某种字符串转换?
当前回答
你总是可以创建准字面量,包含你想要的值的常量:
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);
其他回答
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}");
在@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的建议,使用十六进制字面量。如果您经常使用二进制数,以至于这成为一个问题,那么值得您花点时间来掌握十六进制的诀窍。
如果您需要在源代码中看到二进制数字,我建议像上面那样添加带有二进制文字的注释。
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,
}
:-) 尼尔
从Visual Studio 2017 (c# 7.0)开始,您可以使用0b000001
虽然字符串解析解决方案是最流行的,但我不喜欢它,因为在某些情况下,解析字符串会极大地影响性能。
当需要一种位域或二进制掩码时,我宁愿这样写
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;
}
}