zoukankan      html  css  js  c++  java
  • UTF-8 和 gb2312编码转换

            /// <summary>
            /// 编码转换
            /// </summary>
            /// <param name="TheString">字符</param>
            /// <returns></returns>
            private byte[] StringToBytes(string TheString)
            {
                Encoding FromEncoding = Encoding.GetEncoding("UTF-8");
                Encoding ToEncoding = Encoding.GetEncoding("gb2312");
                byte[] FromBytes = FromEncoding.GetBytes(TheString);
                byte[] Tobytes = Encoding.Convert(FromEncoding,ToEncoding,FromBytes);//编码转换
                return Tobytes;
            }
    
            /// <summary>
            /// 编码转换
            /// </summary>
            /// <param name="TheString">字符</param>
            /// <returns></returns>
            private string BytesToString(byte[] FromBytes)
            {
                Encoding FromEncoding = Encoding.GetEncoding("gb2312");
                Encoding ToEncoding = Encoding.GetEncoding("UTF-8");
                byte[] Tobytes = Encoding.Convert(FromEncoding, ToEncoding, FromBytes);//编码转换
                string str = ToEncoding.GetString(Tobytes);
                return str;
            }
            /// <summary>
            /// 字符串 转换为 gb2312 编码
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button1_Click(object sender, EventArgs e)
            {
                byte[]by = StringToBytes(this.textBox1.Text);
                for (int i = 0; i < by.Length;i++ )
                {
                    string vv = by[i].ToString("X");
                    textBox2.AppendText("0x" + (vv.Length==1?"0"+vv:vv) +" " );
                }
            }
    
            /// <summary>
            /// gb2312 编码 转换为 字符串
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button2_Click(object sender, EventArgs e)
            {
                string str = this.textBox2.Text.Replace("0x", "").Replace(" ", ""); ;
                byte[] by = new byte[str.Length / 2];
                for (int i = 0; i < str.Length / 2;i++ )
                {
                    string vv = str.Substring(i*2,2);
                    by[i] =Convert.ToByte(vv,16);
                }
                string tt =  BytesToString(by);
                this.textBox1.Text = tt;
            }
  • 相关阅读:
    mybatis开始
    14-spring学习-变量操作
    java动态加载jar文件
    Linux下不借助工具实现远程linux服务器上传下载文件
    UML入门
    Linux下打开超大文件的方法
    List和Array相互转换
    redis常用命令
    redis不支持多个数据库实例但是支持多个字典
    如何配置 VirtualBox 中的客户机与宿主机之间的网络连接
  • 原文地址:https://www.cnblogs.com/lanyubaicl/p/11251054.html
Copyright © 2011-2022 走看看