您的位置:首页 > 其它

字符字节转换器,不同编码下字符字节互转

2015-09-23 15:43 405 查看
public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

Encoding enc;

private void textBox2_TextChanged(object sender, EventArgs e)

{

string text = textBox2.Text;

byte[] bt = enc.GetBytes(text);

textBox1.Text = byteToHexStr(bt);

label1.Text = string.Format("字符长度:{0}个字符\n字节个数:{1}字节", textBox2.Text.Length, bt.Length);

}

/// <summary>

/// 字节数组转16进制字符串

/// </summary>

/// <param name="bytes"></param>

/// <returns></returns>

public static string byteToHexStr(byte[] bytes)

{

string returnStr = "";

if (bytes != null)

{

for (int i = 0; i < bytes.Length; i++)

{

returnStr += bytes[i].ToString("X2");

}

}

return returnStr;

}

public static byte[] hexStringToByte(String hex)

{

int len = (hex.Length / 2);

byte[] result = new byte[len];

char[] achar = hex.ToUpper().ToCharArray();

for (int i = 0; i < len; i++)

{

int pos = i * 2;

result[i] = (byte)(toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));

}

return result;

}

private static byte toByte(char c)

{

byte b = (byte)"0123456789ABCDEF".IndexOf(c);

return b;

}

private void textBox1_TextChanged(object sender, EventArgs e)

{

byte[] bt = hexStringToByte(textBox1.Text.Replace(" ", ""));

string text = enc.GetString(bt);

textBox2.Text = text;

label1.Text = string.Format("字符长度:{0}个字符\n字节个数:{1}字节", textBox2.Text.Length, bt.Length);

}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

{

switch (comboBox1.Text.ToString())

{

case "ASCII": enc = Encoding.ASCII; break;

case "GB2312": enc = Encoding.GetEncoding("GB2312"); break;

case "GBK": enc = Encoding.GetEncoding("GBK"); break;

case "UTF-8": enc = Encoding.UTF8; break;

case "Unicode": enc = Encoding.Unicode; break;

default: throw new Exception("未知编码");

}

}

private void Form1_Load(object sender, EventArgs e)

{

enc = Encoding.ASCII;

}

}

图如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: