應用一:轉換爲十六進制字符串
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字符串
2 {
3 return Convert.ToBase64String(bytes);
4 }
應用三:轉換爲基礎數據類型
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...),可以如上進行擴展。
應用四:轉換爲指定編碼的字符串
2 {
3 return encoding.GetString(data);
4 }
應用五: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 }
應用六:位運算
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 }
應用七:保存爲文件
2 {
3 File.WriteAllBytes(path, data);
4 }
應用八:轉換爲內存流
2 {
3 return new MemoryStream(data);
4 }
能想到的就這麼多了!歡迎大家補充!