c# byte[] 到string
例子
byte[] b=new byte[]{0x1f,0x1e,0xcc};
用了一个函数 函数.toString(b);
最后输出的是:1f-1e-cc
这个函数是什么函数
但 好像不是 Convert.ToString(b) Convert.ToString(b)输出的是System.Byte[] 展开
其实可以自己写
0x表示是16进制,后面的就是16进制的数字
1f=31;1e=30;cc=204;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string From10To16(int x)
{
List<string> lss = new List<string>();
while (x >= 16)
{
string y = (x % 16).ToString();
switch (y)
{
case "10": y = "a"; break;
case "11": y = "b"; break;
case "12": y = "c"; break;
case "13": y = "d"; break;
case "14": y = "e"; break;
case "15": y = "f"; break;
}
lss.Add(y);
x = x / 16;
}
string z = x.ToString();
switch (x.ToString())
{
case "10": z = "a"; break;
case "11": z = "b"; break;
case "12": z = "c"; break;
case "13": z = "d"; break;
case "14": z = "e"; break;
case "15": z = "f"; break;
}
lss.Add(z);
string result = "";
for (int i = lss.Count-1; i >=0; i--)
{
result+=lss[i];
}
return result;
}
private void Form1_Load(object sender, EventArgs e)
{
string x="";
byte[] b = new byte[] { 0x1f, 0x1e, 0xcc };
for (int i = 0; i < b.Length; i++)
{
short c= Convert.ToInt16(b[i]);
x += From10To16(c) + "-";
}
if (MessageBox.Show(x.TrimEnd('-')) == DialogResult.OK) { this.Close(); };
}
}
}
System.Text.Encoding.Default.GetString(byteArray)
System.Text.Encoding.ASCII.GetString(byteArray)
System.Text.Encoding.UTF8.GetString(byteArray);
using System.Text;
将一个包含ASCII编码字符的Byte数组转化为一个完整的String
public static string FromASCIIByteArray(byte[] characters)
{
ASCIIEncoding encoding = new ASCIIEncoding( );
string constructedString = encoding.GetString(characters);
return (constructedString);
}
将一个包含Unicode编码字符的Byte数组转化为一个完整的String:
public static string FromUnicodeByteArray(byte[] characters)
{
UnicodeEncoding encoding = new UnicodeEncoding( );
string constructedString = encoding.GetString(characters);
return (constructedString);
}
public static string HexStr2(byte[] data)
{
char[] lookup = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int i = 0, p = 0, l = data.Length;
char[] c = new char[l * 2];
byte d;
while (i < l)
{
d = data[i++];
c[p++] = lookup[d / 0x10];
c[p++] = lookup[d % 0x10];
}
return new string(c, 0, c.Length);
}