http://www.codeproject.com/Tips/1080310/Csharp-Binary-Literal-Helper-Class
C#目前不支持二进制数据直接赋值
int bits=0b00010101;
如果可以直接赋值,那么在按位运算的时候将会带来很大的方便,所以你可以通过这个类来达到直接将二进制文本给变量赋值的目的
1 public static class BinaryLiteral 2 { 3 public static byte ToByte(string str) 4 { 5 return (byte)ToInt64(str, sizeof(byte)); 6 } 7 8 public static short ToInt16(string str) 9 {10 return (short)ToInt64(str, sizeof(short));11 }12 13 public static int ToInt32(string str)14 {15 return (int)ToInt64(str, sizeof(int));16 }17 18 public static long ToInt64(string str)19 {20 return ToInt64(str, sizeof(long));21 }22 23 private static long ToInt64(string str, int sizeInBytes)24 {25 int sizeInBits = sizeInBytes * 8;26 int bitIndex = 0;27 long result = 0;28 29 for (int i = str.Length - 1; i >= 0; i--)30 {31 if (str[i] != ' ')32 {33 if (bitIndex == sizeInBits)34 {35 throw new OverflowException("binary literal too long: " + str);36 }37 38 if (str[i] == '1')39 {40 result |= 1L << bitIndex;41 }42 else if (str[i] != '0')43 {44 throw new InvalidCastException("invalid character in binary literal: " + str[i]);45 }46 47 bitIndex++;48 }49 }50 51 return result;52 }53 }
你可以这样使用它们
1 byte myByteBitMask = BinaryLiteral.ToByte(" 0110 1100");2 short myInt16BitMask = BinaryLiteral.ToInt16(" 1000 0000 0110 1100");3 int myInt32BitMask = BinaryLiteral.ToInt32(" 0101 1111 1000 0000 0110 1100");4 long myInt64BitMask = BinaryLiteral.ToInt64(" 0101 1111 1000 0000 0110 1100");
还可以通过扩展方法,使赋值更简便
public static int ToInt32(this string str) { return (int)ToInt64(str, sizeof(int)); }
int myInt32BitMask2 = " 0101 1111 1000 0000 0110 1100".ToInt32();
你可以将二进制数据中的分隔符用下划线或者别的符号表示,只需要将ToInt64方法中的空格符的判断条件改成对应的判断就行
该类有一个局限性是不能用作const常量的初始化,但是你可以为static readonly只能变量赋值
原标题:二进制文本转换帮助类
关键词: