首頁 >後端開發 >C++ >如何在 C# 中將位元組數組轉換為十六進位字串?

如何在 C# 中將位元組數組轉換為十六進位字串?

Patricia Arquette
Patricia Arquette原創
2025-01-20 11:26:131039瀏覽

How Can I Convert a Byte Array to a Hexadecimal String in C#?

C# 位元組數組到十六​​進位字串轉換技術

本文探討了在 C# 中將位元組數組轉換為其等效的十六進位字串的有效方法。

方法 1:利用 BitConverter

BitConverter 類別提供了一個簡單的方法。 以下範例展示了其用法:

<code class="language-csharp">byte[] byteArray = { 1, 2, 4, 8, 16, 32 };

string hexString = BitConverter.ToString(byteArray);

Console.WriteLine(hexString); // Output: 01-02-04-08-10-20</code>

注意分隔十六進位值的連字號。要消除這些,請使用 Replace():

<code class="language-csharp">hexString = BitConverter.ToString(byteArray).Replace("-", "");

Console.WriteLine(hexString); // Output: 010204081020</code>

方法二:利用Base64編碼

另一種方法是採用 Base64 編碼。 Base64 將二進位資料轉換為 ASCII 字串。 這種方法通常會產生更緊湊的結果:

<code class="language-csharp">string base64String = Convert.ToBase64String(byteArray);

Console.WriteLine(base64String); // Output: AQIECBAg</code>

選擇最適合您需求的方法; Base64 通常更節省空間,而 BitConverter 提供直接的十六進位表示。

以上是如何在 C# 中將位元組數組轉換為十六進位字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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