c#擴展方法奇思妙用基礎篇三:byte 常用擴展

 

 應用一:轉換爲十六進制字符串

 1     public static string ToHex(this byte b)
 2     {
 3         return b.ToString("X2");
 4     }
 5 
 6     public static string ToHex(this IEnumerable<byte> bytes)
 7     {
 8         var sb = new StringBuilder();
 9         foreach (byte b in bytes)
10             sb.Append(b.ToString("X2"));
11         return sb.ToString();
12     }

 第二個擴展返回的十六進制字符串是連着的,一些情況下爲了閱讀方便會用一個空格分開,處理比較簡單,不再給出示例。


 應用二:轉換爲Base64字符串 

1     public static string ToBase64String(byte[] bytes)
2     {
3         return Convert.ToBase64String(bytes);
4     }

 

 應用三:轉換爲基礎數據類型 

1     public static int ToInt(this byte[] value, int startIndex)
2     {
3         return BitConverter.ToInt32(value, startIndex);
4     }
5     public static long ToInt64(this byte[] value, int startIndex)
6     {
7         return BitConverter.ToInt64(value, startIndex);
8     }

  BitConverter類還有很多方法(ToSingle、ToDouble、ToChar...),可以如上進行擴展。

 

 應用四:轉換爲指定編碼的字符串 

1     public static string Decode(this byte[] data, Encoding encoding)
2     {
3         return encoding.GetString(data);
4     }

 

 

 應用五:Hash

 1     //使用指定算法Hash
 2     public static byte[] Hash(this byte[] data, string hashName)
 3     {
 4         HashAlgorithm algorithm;
 5         if (string.IsNullOrEmpty(hashName)) algorithm = HashAlgorithm.Create();
 6         else algorithm = HashAlgorithm.Create(hashName);
 7         return algorithm.ComputeHash(data);
 8     }
 9     //使用默認算法Hash
10     public static byte[] Hash(this byte[] data)
11     {
12         return Hash(data, null);
13     }

 

 應用六:位運算

 1     //index從0開始
 2     //獲取取第index是否爲1
 3     public static bool GetBit(this byte b, int index)
 4     {
 5         return (b & (1 << index)) > 0;
 6     }
 7     //將第index位設爲1
 8     public static byte SetBit(this byte b, int index)
 9     {
10         b |= (byte)(1 << index);
11         return b;
12     }
13     //將第index位設爲0
14     public static byte ClearBit(this byte b, int index)
15     {
16         b &= (byte)((1 << 8- 1 - (1 << index));
17         return b;
18     }
19     //將第index位取反
20     public static byte ReverseBit(this byte b, int index)
21     {
22         b ^= (byte)(1 << index);
23         return b;
24     }

 

 應用七:保存爲文件 

1     public static void Save(this byte[] data, string path)
2     {
3         File.WriteAllBytes(path, data);
4     }

 

 

 應用八:轉換爲內存流 

1     public static MemoryStream ToMemoryStream(this byte[] data)
2     {
3         return new MemoryStream(data);
4     }

 

 

  能想到的就這麼多了!歡迎大家補充!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章