如何在 C# 中將字串轉換為位元組陣列

如何在 C# 中將字串轉換為位元組陣列

本文將介紹在 C# 中把一個字串轉換為位元組陣列的方法。

  • 使用 GetBytes() 方法

在 C# 中使用 GetBytes() 方法將字串轉換為位元組陣列

在 C# 中,我們可以使用 Encoding 類的 GetBytes() 方法將字串轉換為位元組陣列。我們可以將多種編碼轉換為位元組陣列。這些編碼是 ASCIIUnicodeUTF32 等。此方法有多個過載。在這種情況下,我們將使用以下過載。使用此方法的正確語法如下。

Encoding.GetBytes(String stringName);

方法 GetBytes() 的這個過載只有一個引數。它的詳細引數如下。

引數 說明
stringName 強制 這是我們要轉換為位元組陣列的字串

這個函式返回一個以位元組為單位的代表給定字串的位元組陣列。

下面的程式顯示了我們如何使用 GetBytes() 方法將字串轉換為位元組陣列。

using System;
using System.Text;

class StringToByteArray {
  static void Main(string[] args) {
    string myString = "This is a string.";
    byte[] byteArray = Encoding.ASCII.GetBytes(myString);
    Console.WriteLine("The Byte Array is:");
    foreach (byte bytes in byteArray) {
      Console.WriteLine(bytes);
    }
  }
}

輸出:

The Byte Array is:
84
104
105
115
32
105
115
32
97
32
115
116
114
105
110
103
46
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相關文章 - Csharp String

相關文章 - Csharp Array