using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HanZiEncoding
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//将汉字转换成GB2312编码
private byte[] StringToBytes(string TheString)
{
Encoding fromEcoding = Encoding.GetEncoding("UTF-8");//返回utf-8的编码
Encoding toEcoding = Encoding.GetEncoding("gb2312");
byte[] fromBytes = fromEcoding.GetBytes(TheString);
byte[] tobytes = Encoding.Convert(fromEcoding, toEcoding, fromBytes);//将字节数组从一种编码转换为另一种编码
return tobytes;
}
//将GB2312编码转换成汉字
private string BytesToString(byte[] bytes)
{
string myString;
Encoding fromEcoding = Encoding.GetEncoding("gb2312");
Encoding toEcoding = Encoding.GetEncoding("UTF-8");
byte[] toBytes = Encoding.Convert(fromEcoding, toEcoding, bytes);
myString = toEcoding.GetString(toBytes);//将字节数组解码成字符串
return myString;
}
private void button1_Click(object sender, EventArgs e)
{
byte[] stringToByte = StringToBytes(textBox1.Text);
textBox2.Text = "";
foreach(byte myByte in stringToByte)
{
string Str = myByte.ToString("x").ToUpper();
textBox2.Text += "0x" + (Str.Length == 1 ? "0" + Str : Str) + " ";
}
}
private void button2_Click(object sender, EventArgs e)
{
byte[] data = new byte[textBox3.Text.Length / 2];
int i;
try
{
string buffer = textBox3.Text;
buffer = buffer.Replace("0x", string.Empty);
buffer = buffer.Replace(" ", string.Empty);
for (i = 0; i < buffer.Length / 2; i++)
{
data[i] = Convert.ToByte(buffer.Substring(i * 2, 2), 16);
}
textBox4.Text = BytesToString(data);
}
catch (Exception)
{
MessageBox.Show("数据转换错误,请输入数字");
}
}
}
}