如何在 C# 中将字节数组转换为字符串?

csharpserver side programmingprogramming更新于 2025/4/20 9:22:17

在 .Net 中,每个字符串都有一个字符集和编码。字符编码告诉计算机如何将原始零和一解释为真实字符。它通常通过将数字与字符配对来实现这一点。实际上,它是将一组 Unicode 字符转换为字节序列的过程。

我们可以使用 Encoding.GetString 方法 (Byte[]) 将指定字节数组中的所有字节解码为字符串。Encoding 类中还提供其他几种解码方案,例如 UTF8、Unicode、UTF32、ASCII 等。Encoding 类作为 System.Text 命名空间的一部分提供。

string result = Encoding.Default.GetString(byteArray);

示例

using System;
using System.Text;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         byte[] byteArray = Encoding.Default.GetBytes("Hello World");
         Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}");
         string str = Encoding.Default.GetString(byteArray);
         Console.WriteLine($"String is: {str}");
         Console.ReadLine();
      }
   }
}

输出

上述代码的输出是

Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: Hello World

需要注意的是,我们应该在两个方向上使用相同的编码。例如,如果字节数组使用 ASCII 编码,而我们尝试使用 UTF32 获取字符串,我们将无法获得所需的字符串。

示例

using System;
using System.Text;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         byte[] byteArray = Encoding.ASCII.GetBytes("Hello World");
         Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}");
         string str = Encoding.UTF32.GetString(byteArray);
         Console.WriteLine($"String is: {str}");
         Console.ReadLine();
      }
   }
}

输出

上述代码的输出是

Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: ???

相关文章