📜  c# 字符串代码 ascii - C# (1)

📅  最后修改于: 2023-12-03 15:29:47.361000             🧑  作者: Mango

C# 字符串代码 ascii

在 C# 中,字符串是一种常用的数据类型。常常需要将字符串转换成 ASCII 码或将 ASCII 码转换成字符串。本文将介绍如何在 C# 中进行字符串与 ASCII 码的转换。

字符串转 ASCII 码

在 C# 中,可以使用 Encoding.ASCII.GetBytes() 方法将字符串转换成 ASCII 码。例如,将字符串 "Hello World" 转换成 ASCII 码:

string str = "Hello World";
byte[] asciiBytes = Encoding.ASCII.GetBytes(str);

上述代码中,str 是需要转换的字符串,asciiBytes 是转换后得到的字节数组。

ASCII 码转字符串

在 C# 中,可以使用 Encoding.ASCII.GetString() 方法将 ASCII 码转换成字符串。例如,将字节数组 {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100} 转换成字符串:

byte[] asciiBytes = new byte[] {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
string str = Encoding.ASCII.GetString(asciiBytes);

上述代码中,asciiBytes 是需要转换的字节数组,str 是转换后得到的字符串。

需要注意的是,Encoding.ASCII 只支持 ASCII 码。如果需要支持其他字符集,需要使用 Encoding.UTF8 等其他编码方式。

以上就是在 C# 中进行字符串与 ASCII 码转换的方法。