c#怎么将byte数组转成string

供稿:hz-xin.com     日期:2025-05-22
c#怎么把byte数组转换为字符串

有两张方法:
方法一:
//字符串转byte
string StringMessage = "How Are you?";
Console.WriteLine("{0}", StringMessage);
System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
Byte[] BytesMessage = ASCII.GetBytes(StringMessage);
//byte转字符串
Byte[] BytesMessage;
System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
String StringMessage = ASCII.GetString( BytesMessage );

方法二:
//字符串转UTF-8 byte
string StringMessage = "Hello World How Are you? Pi /u03C0 Yen /uFFE5";
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
Byte[] BytesMessage = UTF8.GetBytes(StringMessage);
//UTF-8 byte 转字符串
Byte[] BytesMessage;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
String StringMessage = UTF8.GetString( BytesMessage );

c#中byte数组转化char数组方法如下:
//定义一个byte数组,并初始化
byte[]
b=new
byte[5]{0x01,0x02,0x03,0x04,0x05};
//用encoding的ascii方法的getchars函数依次取得b并转换成char数组。
char[]
c=encoding.ascii.getchars(b);

首先要先知道你的byte数组是基于什么编码方式生成的,然后才能根据这种编码方式转回string
例:byte[] bytes = System.Text.Encoding.UTF8.GetBytes("要转换成byte数组的字符串");//这里根据utf-8的编码形式将字符串转换成byte流,如果想转换回正确的字符串,也必须是utf-8的编码,否则转换成功也是乱码
string s = System.Text.Encoding.UTF8.GetString(bytes);//这里将byte数组转回字符串