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