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:

  1. Convert a byte array into a string using GetString(byte[] bytes).
  2. Convert the string into a byte array using GetBytes(string s).
  3. Properties such as Encoding.UTF8 and Encoding.ASCII: obtain an Encoding object for a specific encoding format.
  4. Retrieve an Encoding object based on the encoding name.
  5. 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!
bannerAds