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

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

Patricia Arquette
發布: 2025-01-20 11:26:13
原創
1038 人瀏覽過

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板