文章出處

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只讀變量賦值

 


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()