byte转化为string(byte数组转换成string怎么转换 C#)

本文目录
byte数组转换成string怎么转换 C#
实现字节数组至十六进制字符串转换,这个操作在接收网络数据时非常有用,代码嘛,就一行,就一行,就一行:
string str = BitConverter.ToString(bytes);
字节数组怎么转string
1.Convert.ToBase64String与 Convert.FromBase64String
此方法简单实用。转换成的string包含:26个英文字母的大小写、+、/、0~9的数字,总共64个字符。一般会在结尾出现“=”。分析其原因很简单。
原理:用64个字符来描述6bit的二进制。
方式:把byte数据连在一起,以6bit为单位进行分组,使用64个字符描述6bit数据,如果分组不足6bit,使用“=”补全。
2.自己写代码,使用16进制字符0~9、A~F来描述数据。
原理:使用16个字符来描述4bit的二进制。也就是说,一个byte要使用两个16进制字符来进行描述。
方式:对每一byte的前半部分与后半部分分别用字符来描述。
此方法需要自己手动进行书写,代码相当简单。可以Crtl+c Ctrl+v拿来就用。
public static string ByteToString(byte bytes)
{
StringBuilder strBuilder = new StringBuilder();
foreach (byte bt in bytes)
{
strBuilder.AppendFormat("{0:X2}", bt);
}
return strBuilder.ToString();
}
public static byte StringToByte(string str)
{
byte;
for (int i = 0; i 《 str.Length / 2; i++)
{
int btvalue = Convert.ToInt32(str.Substring(i * 2, 2), 16);
bytes = (byte)btvalue;
}
return bytes;
}
3.使用Encoding的编码自动转化Encoding.GetEncoding("编码格式").GetString()和 Encoding.GetEncoding("编码格式").GetBytes()
原理:使用规则强行转换。
方式:使用自身的编码方式进行转换,转换出来的byte数据或者是string会出现各种奇怪或者是不可见的字符,存贮起来非常不方便。
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 );

更多文章:
force-unicode-font是什么意思?ღ᭄ꦿ这些特殊字是怎么来的
2026年9月27日 23:50
java重载和覆盖的定义(java中方法重载和重写的区别和定义)
2026年9月27日 22:50
变幻金刚魔方教程图解(变幻金刚魔方的最后一步,研究了很长时间就是搞不 出来,能教教我吗)
2026年9月27日 21:00
怎样使用dreamweaver(怎么用dreamweaver制作网页如何用dreamweaver制作网页)
2026年9月27日 20:40
css提交按钮怎么写(html:submit能加css样式吗)
2026年9月27日 19:20
雨崩近年危险事件调查(下雨好长时间了,去雨崩的路况怎么样有刚从雨崩回来的吗)
2026年9月27日 13:20
shell脚本substr(SHELL脚本对LINUX下指定文本文件的满足条件的行的特定位置字符串进行替换)
2026年9月27日 10:50





