c# string 转utf8
时间: 2023-08-07 10:04:18 浏览: 54
在 C# 中,可以使用 `Encoding.UTF8.GetBytes()` 方法将字符串转换为 UTF-8 编码的字节数组。以下是一个示例代码:
```csharp
using System;
using System.Text;
class Program
{
static void Main()
{
string str = "Hello, world!";
byte[] utf8Bytes = Encoding.UTF8.GetBytes(str);
foreach (byte b in utf8Bytes)
{
Console.Write($"{b:X2} ");
}
Console.WriteLine();
}
}
```
在上述示例中,我们首先声明了一个字符串 `str`,然后使用 `Encoding.UTF8.GetBytes()` 方法将其转换为 UTF-8 编码的字节数组 `utf8Bytes`。最后,我们通过循环遍历字节数组,并使用十六进制格式打印每个字节的值。
运行上述代码,输出将是 UTF-8 编码的字节数组表示形式。请注意,UTF-8 编码使用变长字节表示字符,因此一个字符可能由多个字节组成。
相关问题
HEX 转 UTF8 c#
以下是C#中将HEX转换为UTF8的示例代码:
```csharp
// 将HEX字符串转换为byte数组
byte[] bytes = Enumerable.Range(0, hexString.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
.ToArray();
// 将byte数组转换为UTF8编码的字符串
string utf8String = Encoding.UTF8.GetString(bytes);
```
其中,`hexString`是输入的HEX字符串,`utf8String`是输出的UTF8编码的字符串。
c# string转byte
可以使用Encoding类来将字符串转换为字节数组。以下是一个示例代码:
```csharp
string str = "Hello, World!";
byte[] bytes = Encoding.UTF8.GetBytes(str);
```
在上面的示例中,我们使用UTF8编码将字符串转换为字节数组。你可以根据需要选择不同的编码方式。