How is encoding used in C#?
In C#, the Encoding class is used to convert text strings to byte arrays or byte arrays to text strings. It includes various encoding formats such as ASCII, UTF-8, UTF-16, etc., allowing users to choose the appropriate encoding format for conversion as needed.
Here are some common methods and attributes of the Encoding class:
- Convert a byte array into a string using GetString(byte[] bytes).
- Convert the string into a byte array using GetBytes(string s).
- Properties such as Encoding.UTF8 and Encoding.ASCII: obtain an Encoding object for a specific encoding format.
- Retrieve an Encoding object based on the encoding name.
- Encoding.Default: Obtain the system’s default encoding format.
The sample code is shown below:
// 将字符串转换为字节数组
string str = "Hello, World!";
byte[] bytes = Encoding.UTF8.GetBytes(str);
// 将字节数组转换为字符串
string newStr = Encoding.UTF8.GetString(bytes);
Console.WriteLine(newStr); // 输出:Hello, World!