有效地轉換字節數組和十六進製字符串
>許多應用需要將字節陣列轉換為十六進製字符串,反之亦然。 本文探討了.net中此轉換的有效方法。
字節數組到十六進製字符串
>
Convert.ToHexString
.NET 5及以後提供最簡單的解決方案:
byte[] byteArray = { 1, 2, 3 }; string hexString = Convert.ToHexString(byteArray);
>
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(); }
>
十六進製字符串到字節數組public static string ByteArrayToHex(byte[] ba) { return BitConverter.ToString(ba).Replace("-", ""); }
>可以通過此方法將十六進制的字符串轉換回字節數組:
為增強性能,使用
>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; }
以上是如何有效地將字節陣列轉換為十六進製字符串,反之亦然?的詳細內容。更多資訊請關注PHP中文網其他相關文章!