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;
        }

 

posted @ 2019-07-26 16:14  蓝雨冰城  阅读(562)  评论(0编辑  收藏  举报