C# 实现汉字与GB2312编码的转换

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("数据转换错误,请输入数字");
            }
        }
    }
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值