C#将byte[]数组转换成字符串打印输出
时间: 2023-11-22 08:04:18 浏览: 37
可以使用Encoding类中的GetString方法将byte[]数组转换为字符串,然后通过Console.WriteLine方法打印输出。示例代码如下:
```
byte[] byteArray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 };
string str = Encoding.UTF8.GetString(byteArray);
Console.WriteLine(str);
```
输出结果为:
```
Hello World!
```
相关问题
C# 将Byte数组转为字符串
C#中可以使用BitConverter.ToString()方法将Byte数组转换为字符串,该方法返回一个由十六进制值组成的字符串,每个值之间用“-”隔开。如果需要去掉“-”,可以使用String.Replace()方法。具体代码如下:
```
byte[] vals = { 0x01, 0xAA, 0xB1,0xDC, 0x10, 0xDD };
string str = BitConverter.ToString(vals).Replace("-", "");
Console.WriteLine(str);
```
输出结果为:01AAB1DC10DD。
C# byte数组转字符串
以下是两种C# byte数组转字符串的方法:
1. 使用Encoding类的GetString方法可以将字节数组解码为字符串。
```csharp
byte[] byteArray = { 72, 101, 108, 108, 111 }; // 字节数组
string str = Encoding.ASCII.GetString(byteArray); // 将字节数组转换为ASCII编码的字符串
Console.WriteLine(str); // 输出:Hello
```
2. 将字节数组转换为十六进制字符串,然后再将其转换为字节数组。
```csharp
byte[] byteArray = { 72, 101, 108, 108, 111 }; // 字节数组
string hexString = BitConverter.ToString(byteArray); // 将字节数组转换为十六进制字符串
string[] hexValuesSplit = hexString.Split('-'); // 将十六进制字符串按照“-”分割
byte[] decBytes = new byte[hexValuesSplit.Length];
for (int i = 0; i < hexValuesSplit.Length; i++)
{
decBytes[i] = Convert.ToByte(hexValuesSplit[i], 16); // 将十六进制字符串转换为字节数组
}
string str = Encoding.ASCII.GetString(decBytes); // 将字节数组转换为ASCII编码的字符串
Console.WriteLine(str); // 输出:Hello
```