C#之windows桌面软件第八课:汉字(GB2312)与编码(UTF-8)之间的相互转换
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;
/*
(1)ASSIC码是一个字节的,一个汉字占两个字节,所以ASSIC不可以表示汉字。ASSIC码只能表示256个数。
(2)咱们国家用的是GB2132国标库编码方式,而VS2017平台用的是UTF-8编码方式,所以先得把UTF-8编码转换为GB2132编码才可以显示出来。
*/
namespace 汉字显示
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
/***********utf8编码转为GB2132编码*************/
private byte[] StringToBytes(string TheString)
{
//定义UTF8和GB2312编码对象
Encoding FromEcoding = Encoding.GetEncoding("UTF-8"); //UTF8编码
Encoding ToEcoding = Encoding.GetEncoding("gb2312"); //GB2312编码
//把UTF-8的字符串转换为UTF-8类型的字节码
byte[] FromBytes = FromEcoding.GetBytes(TheString); //FromBytes存的是汉字UTF8字节序列
//把UTF-8类型的字节码转换为GB2132字节码(Tobytes存放的是GB2132字节码)
byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, FromBytes);
return Tobytes;
}
/***********GB2132编码转为utf8编码*************/
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); //得到的是UTF8字节码序列,需要转换为UTF8字符串
return Mystring;
}
//汉字-》编码的转换按钮
private void button1_Click(object sender, EventArgs e)
{
byte[] StringsToByte = StringToBytes(textBox1.Text); //得到字符串的GB2132字节编码。(textBox1为汉字输入框)
textBox2.Text = "";
foreach (byte MyByte in StringsToByte) //遍历StringsToByte数组放在MyByte变量中
{
string Str = MyByte.ToString("x").ToUpper(); //转换为16进制大写字符串放在Str中
textBox2.Text += "0x" + (Str.Length == 1 ? "0" + Str : Str) + " "; //textBox2为编码输出框
}
}
//编码-》汉字的转换按钮
private void button2_Click(object sender, EventArgs e)
{
byte[] data = new byte[textBox3.Text.Length / 2];
int i;
try //如果此时用户输入字符串中含有非法字符(字母,汉字,符号等等,try,catch块可以捕捉并提示)
{
string buffer = textBox3.Text;//把textBox3框中输入的编码存放在buffer字符串变量中。
//为了保证汉字转编码输出结果(0xXX)可以通用,所以程序允许输入0xXX(可以带空格),程序会将0x和空格自动去除
buffer = buffer.Replace("0x", ""); //用空字符串代替0X
buffer = buffer.Replace(" ", string.Empty);//string.Empty等同于上面的 ""
for (i = 0; i < buffer.Length / 2; i++) //转换偶数个
{
data[i] = Convert.ToByte(buffer.Substring(i * 2, 2), 16); //转换为16进制
}
textBox4.Text = BytesToString(data); //把byte型数据转换为String类型数据,并输出给textBox4框
}
catch
{
MessageBox.Show("数据转换错误,请输入数字。", "错误");
}
}
}
}
www.DoYoung.net(部分代码来至杜洋工作室)