掌握字節數組和.net
中的十六進製字符串轉換 .NET開發人員經常遇到需要在字節陣列和十六進製字符串之間進行轉換的需要。本指南探討了這些轉換的有效方法。
將字節陣列轉換為十六進制>
從.net 5開始,提供了最簡單,最有效的解決方案:Convert.ToHexString
<code class="language-csharp">string hexString = Convert.ToHexString(byteArray);</code>
其中
被定義為:<code class="language-csharp">hexString = ByteArrayToHex(byteArray);</code>>
ByteArrayToHex
另一個可行的選擇,儘管效率可能較低:
<code class="language-csharp">public static string ByteArrayToHex(byte[] ba) { StringBuilder hex = new StringBuilder(ba.Length * 2); foreach (byte b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString(); }</code>將十六進製字符串轉換為字節陣列
<code class="language-csharp">hexString = BitConverter.ToString(byteArray).Replace("-", "");</code>
> 反向轉換同樣重要:>
函數可以用作:<code class="language-csharp">byte[] byteArray = HexToStringArray(hexString);</code>>
HexToStringArray
<code class="language-csharp">public static byte[] HexToStringArray(string hex) { int numChars = hex.Length; byte[] bytes = new byte[numChars / 2]; for (int i = 0; i < numChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; }</code>
為了獲得最佳性能,尤其是在大型數據集的情況下,請避免使用>>>。直接迭代和位操縱可提供大量的性能改進。
以上是如何有效地轉換.NET中的字節陣列和十六進製字符串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!