C# byte數(shù)組常用擴展淺析
C# byte數(shù)組常用擴展應用一:轉換為十六進制字符串
- public static string ToHex(this byte b)
- {
- return b.ToString("X2");
- }
- public static string ToHex(this IEnumerable<byte> bytes)
- {
- var sb = new StringBuilder();
- foreach (byte b in bytes)
- sb.Append(b.ToString("X2"));
- return sb.ToString();
- }
第二個擴展返回的十六進制字符串是連著的,一些情況下為了閱讀方便會用一個空格分開,處理比較簡單,不再給出示例。
C# byte數(shù)組常用擴展應用二:轉換為Base64字符串
- public static string ToBase64String(byte[] bytes)
- {
- return Convert.ToBase64String(bytes);
- }
C# byte數(shù)組常用擴展應用三:轉換為基礎數(shù)據(jù)類型
- public static int ToInt(this byte[] value, int startIndex)
- {
- return BitConverter.ToInt32(value, startIndex);
- }
- public static long ToInt64(this byte[] value, int startIndex)
- {
- return BitConverter.ToInt64(value, startIndex);
- }
BitConverter類還有很多方法(ToSingle、ToDouble、ToChar...),可以如上進行擴展。
C# byte數(shù)組常用擴展應用四:轉換為指定編碼的字符串
- public static string Decode(this byte[] data, Encoding encoding)
- {
- return encoding.GetString(data);
- }
C# byte數(shù)組常用擴展應用五:Hash
- //使用指定算法Hash
- public static byte[] Hash(this byte[] data, string hashName)
- {
- HashAlgorithm algorithm;
- if (string.IsNullOrEmpty(hashName)) algorithm = HashAlgorithm.Create();
- else algorithm = HashAlgorithm.Create(hashName);
- return algorithm.ComputeHash(data);
- }
- //使用默認算法Hash
- public static byte[] Hash(this byte[] data)
- {
- return Hash(data, null);
- }
C# byte數(shù)組常用擴展應用六:位運算
- //index從0開始
- //獲取取第index是否為1
- public static bool GetBit(this byte b, int index)
- {
- return (b & (1 << index)) > 0;
- }
- //將第index位設為1
- public static byte SetBit(this byte b, int index)
- {
- b |= (byte)(1 << index);
- return b;
- }
- //將第index位設為0
- public static byte ClearBit(this byte b, int index)
- {
- b &= (byte)((1 << 8) - 1 - (1 << index));
- return b;
- }
- //將第index位取反
- public static byte ReverseBit(this byte b, int index)
- {
- b ^= (byte)(1 << index);
- return b;
- }
C# byte數(shù)組常用擴展應用七:保存為文件
- public static void Save(this byte[] data, string path)
- {
- File.WriteAllBytes(path, data);
- }
C# byte數(shù)組常用擴展應用八:轉換為內(nèi)存流
- public static MemoryStream ToMemoryStream(this byte[] data)
- {
- return new MemoryStream(data);
- }
C# byte數(shù)組常用擴展的八種情況就向你介紹到這里,希望對你了解和學習C# byte數(shù)組常用擴展有所幫助。
【編輯推薦】