首頁 >後端開發 >C++ >如何有效地將字節陣列轉換為十六進製字符串,反之亦然?

如何有效地將字節陣列轉換為十六進製字符串,反之亦然?

Susan Sarandon
Susan Sarandon原創
2025-02-03 08:09:38259瀏覽

How to Efficiently Convert Byte Arrays to Hexadecimal Strings and Vice Versa?

有效地轉換字節數組和十六進製字符串

>

許多應用需要將字節陣列轉換為十六進製字符串,反之亦然。 本文探討了.net中此轉換的有效方法。

字節數組到十六進製字符串

> Convert.ToHexString.NET 5及以後提供最簡單的解決方案:

<code class="language-csharp">byte[] byteArray = { 1, 2, 3 };
string hexString = Convert.ToHexString(byteArray); </code>
對於較舊的.NET框架,兩個替代方案提供了類似的功能:>

方法1(使用StringBuilder):

>

<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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn