如何在 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