您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“C#下byte數(shù)組常用擴(kuò)展淺析”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
C# byte數(shù)組常用擴(kuò)展應(yīng)用一:轉(zhuǎn)換為十六進(jìn)制字符串
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(); }
第二個(gè)擴(kuò)展返回的十六進(jìn)制字符串是連著的,一些情況下為了閱讀方便會(huì)用一個(gè)空格分開,處理比較簡(jiǎn)單,不再給出示例。
C# byte數(shù)組常用擴(kuò)展應(yīng)用二:轉(zhuǎn)換為Base64字符串
public static string ToBase64String(byte[] bytes) { return Convert.ToBase64String(bytes); }
C# byte數(shù)組常用擴(kuò)展應(yīng)用三:轉(zhuǎn)換為基礎(chǔ)數(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...),可以如上進(jìn)行擴(kuò)展。
C# byte數(shù)組常用擴(kuò)展應(yīng)用四:轉(zhuǎn)換為指定編碼的字符串
public static string Decode(this byte[] data, Encoding encoding) { return encoding.GetString(data); }
C# byte數(shù)組常用擴(kuò)展應(yīng)用五: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); } //使用默認(rèn)算法Hash public static byte[] Hash(this byte[] data) { return Hash(data, null); }
C# byte數(shù)組常用擴(kuò)展應(yīng)用六:位運(yùn)算
//index從0開始 //獲取取第index是否為1 public static bool GetBit(this byte b, int index) { return (b & (1 < 0; } //將第index位設(shè)為1 public static byte SetBit(this byte b, int index) { b |= (byte)(1 << index); return b; } //將第index位設(shè)為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ù)組常用擴(kuò)展應(yīng)用七:保存為文件
public static void Save(this byte[] data, string path) { File.WriteAllBytes(path, data); }
C# byte數(shù)組常用擴(kuò)展應(yīng)用八:轉(zhuǎn)換為內(nèi)存流
public static MemoryStream ToMemoryStream(this byte[] data) { return new MemoryStream(data); }
“C#下byte數(shù)組常用擴(kuò)展淺析”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。