字符串的编码解码技术

对于Unicode字符来说,编码是指将一组Unicode字符串转换成一个字节序列的过程,解码则相反。


例子:以下例子演示了如何列举所有编码方式以及根据给定的编码方式进行编码解码,代码如下:

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 EncoderDecoderExample
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            textBoxOldText.Text = "测试数据:abc,123,我";
            textBoxEncoder.ReadOnly = textBoxDecoder.ReadOnly = true;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //获取所有的编码类型并添加到comboBoxType控件中
            foreach (EncodingInfo ei in Encoding.GetEncodings())
            {
                Encoding en = ei.GetEncoding();
                comboBoxType.Items.Add(string.Format("{0}[{1}]", en.HeaderName, en.EncodingName));
            }
            comboBoxType.SelectedIndex = comboBoxType.FindString("gb2312");
        }

        private void buttonRun_Click(object sender, EventArgs e)
        {
            //根据选中的编码格式进行编码
            String codeType = this.comboBoxType.SelectedItem.ToString();
            codeType = codeType.Substring(0, codeType.IndexOf('['));
            Encoder encoder = Encoding.GetEncoding(codeType).GetEncoder();
            char[] chars = this.textBoxOldText.Text.ToCharArray();
            Byte[] bytes = new Byte[encoder.GetByteCount(chars, 0, chars.Length, true)];
            encoder.GetBytes(chars, 0, chars.Length, bytes, 0, true);
            textBoxEncoder.Text = Convert.ToBase64String(bytes);

            //根据选中的编码格式进行解码
            Decoder decoder = Encoding.GetEncoding(codeType).GetDecoder();
            int charLen = decoder.GetChars(bytes, 0, bytes.Length, chars, 0);
            String strResult = "";
            foreach (char c in chars)
                strResult = strResult + c.ToString();
            textBoxDecoder.Text = strResult;
        }
    }
}

运行后图片:







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值