先决条件:如何在C#中声明和使用byte []?
C#中的字符串到字节数组的转换
在C#中,可以使用Encoding将字符串转换为字节数组。方法,它接受字符串作为参数并返回字节数组。ASCII.GetBytes()
注意:在C#中,字符串每个字符包含两个字节;每个字符包含两个字节。该方法将其转换为1字节。尽管如此,有时仍可能会丢失数据。
语法:
方法编码。包含各种重载方法,这里我们使用以下方法类型...ASCII.GetBytes()
byte[]Encoding.ASCII.GetBytes(String_Object);
示例
本示例包含一个常量字符串,并将其转换为byte []
usingSystem;
usingSystem.Text;
namespaceTest
{
classProgram
{
staticvoidMain(string[]args)
{
stringstr="HelloWorld!Iam[emailprotected]";
//读取所有字符作为字节并将其存储到byte []
byte[]barr=Encoding.ASCII.GetBytes(str);
//使用字节值打印字符
for(intloop=0;loop
{
Console.WriteLine("Byteofchar\'"+str[loop]+"\':"+barr[loop]);
}
//按ENTER退出
Console.ReadLine();
}
}
}
输出结果
Byteofchar'H':72
Byteofchar'e':101
Byteofchar'l':108
Byteofchar'l':108
Byteofchar'o':111
Byteofchar'':32
Byteofchar'W':87
Byteofchar'o':111
Byteofchar'r':114
Byteofchar'l':108
Byteofchar'd':100
Byteofchar'!':33
Byteofchar'':32
Byteofchar'I':73
Byteofchar'':32
Byteofchar'a':97
Byteofchar'm':109
Byteofchar'':32
Byteofchar'I':73
Byteofchar'n':110
Byteofchar'c':99
Byteofchar'l':108
Byteofchar'u':117
Byteofchar'd':100
Byteofchar'e':101
Byteofchar'H':72
Byteofchar'e':101
Byteofchar'l':108
Byteofchar'p':112
Byteofchar'@':64
Byteofchar'1':49
Byteofchar'2':50
Byteofchar'3':51