如何在 C# 中将字符串转换为字节数组
本文将介绍在 C# 中把一个字符串转换为字节数组的方法。
- 使用
GetBytes()
方法
在 C# 中使用 GetBytes()
方法将字符串转换为字节数组
在 C# 中,我们可以使用 Encoding
类的 GetBytes()
方法将字符串转换为字节数组。我们可以将多种编码转换为字节数组。这些编码是 ASCII
,Unicode
,UTF32
等。此方法有多个重载。在这种情况下,我们将使用以下重载。使用此方法的正确语法如下。
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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。