有效地轉換字節數組和十六進製字符串
>許多應用需要將字節陣列轉換為十六進製字符串,反之亦然。 本文探討了.net中此轉換的有效方法。
字節數組到十六進製字符串
>
Convert.ToHexString
.NET 5及以後提供最簡單的解決方案:
<code class="language-csharp">byte[] byteArray = { 1, 2, 3 }; string hexString = Convert.ToHexString(byteArray); </code>對於較舊的.NET框架,兩個替代方案提供了類似的功能:
>
<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>方法2(使用bitConverter):
>
十六進製字符串到字節數組<code class="language-csharp">public static string ByteArrayToHex(byte[] ba) { return BitConverter.ToString(ba).Replace("-", ""); }</code>
>可以通過此方法將十六進制的字符串轉換回字節數組:
為增強性能,使用
><code class="language-csharp">public static byte[] HexToByteArray(string hex) { int len = hex.Length; byte[] arr = new byte[len / 2]; for (int i = 0; i < len; i += 2) { arr[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); } return arr; }</code>直接避免了不必要的中間轉換。 在處理大字節陣列時,這種方法尤其有益。
以上是如何有效地將字節陣列轉換為十六進製字符串,反之亦然?的詳細內容。更多資訊請關注PHP中文網其他相關文章!