C#如何将字符串转换位utf8编码
时间: 2024-02-12 08:08:45 浏览: 20
在C#中,可以使用`System.Text.Encoding.UTF8.GetBytes()`方法将字符串转换为UTF8编码。示例代码如下:
```csharp
string str = "Hello, World!";
byte[] utf8Bytes = Encoding.UTF8.GetBytes(str);
```
在上面的代码中,`str`是要转换的字符串,`utf8Bytes`是转换后的UTF8编码字节数组。
相关问题
c#16进制字符串(UTF8)转字符串
你可以使用C#的`Encoding`类中的`GetString`方法将UTF8编码的16进制字符串转换为字符串。首先,你需要将16进制字符串转换为字节数组,然后使用`Encoding.UTF8.GetString`方法将字节数组转换为字符串。下面是一个示例代码:
```csharp
using System;
using System.Text;
public class Program
{
public static void Main()
{
string hexString = "E4BD" + "A0E5" + "A5BD";
string result = HexToUtf8String(hexString);
Console.WriteLine(result);
}
public static string HexToUtf8String(string hexString)
{
byte[] bytes = new byte = Convert.ToByte(hexString.Substring(i, 2), 16);
}
return Encoding.UTF8.GetString(bytes);
}
}
```
在上面的代码中,我们将16进制字符串`"E4BD" + "A0E5" + "A5BD"`作为示例输入,然后通过`HexToUtf8String`方法将其转换为UTF8编码的字符串。输出结果为`你好`。
希望能对你有所帮助!如果有任何问题,请随时问我。
C#中将字符串转换为字节
在C#中,可以使用Encoding类将字符串转换为字节数组。具体的方法是使用GetBytes()方法,其中可以指定要使用的编码类型。以下是一个示例:
```csharp
string str = "Hello, World!";
byte[] bytes = Encoding.UTF8.GetBytes(str);
```
在上面的示例中,我们将字符串"Hello, World!"转换为UTF-8编码的字节数组。你也可以使用其他编码类型,例如ASCII、Unicode等,只需将Encoding.UTF8替换为相应的编码类型即可。
希望能帮助到你!如果你还有其他问题,请随时提问。