c#汉字与编码之间的转换(输出十六进制)

 /******************************************************************/
        /***********************               ****************************/
        /*********************** 汉字转换工具  ****************************/
        /***********************               ****************************/
        /******************************************************************/


        /****************************  字符串转编码函数 **********************************/
        private byte[] StringToBytes(string TheString)
        {
            Encoding encoding = Encoding.GetEncoding("UTF-8");
            Encoding encoding2 = Encoding.GetEncoding("gb2312");
            byte[] bytes = encoding.GetBytes(TheString);
            return Encoding.Convert(encoding, encoding2, bytes);
        }
        /****************************  编码转字符串函数 **********************************/
        private string BytesToString(byte[] Bytes)
        {
            Encoding encoding = Encoding.GetEncoding("gb2312");
            Encoding encoding2 = Encoding.GetEncoding("UTF-8");
            byte[] bytes = Encoding.Convert(encoding, encoding2, Bytes);
            return encoding2.GetString(bytes);
        }
        /****************************  单击转换按钮事件 **********************************/
        private void Changez_Click(object sender, EventArgs e)
        {
            if (this.CHcode.Checked)//判断什么类型的转换
            {
                byte[] array = this.StringToBytes(this.intextz.Text);
                this.outtextz.Text = "";
                byte[] array2 = array;
                for (int i = 0; i < array2.Length; i++)
                {
                    byte b = array2[i];
                    string text = b.ToString("x").ToUpper();
                    TextBox expr_64 = this.outtextz;
                    expr_64.Text = expr_64.Text + "0x" + ((text.Length == 1) ? ("0" + text) : text) + " ";
                }
            }
            else
            {
                if (!this.CHcode.Checked)
                {
                    byte[] array3 = new byte[this.intextz.Text.Length / 2];
                    try
                    {
                        string text2 = this.intextz.Text;
                        text2 = text2.Replace("0x", "");
                        text2 = text2.Replace(" ", string.Empty);
                        for (int j = 0; j < text2.Length / 2; j++)
                        {
                            array3[j] = Convert.ToByte(text2.Substring(j * 2, 2), 16);
                        }
                        this.outtextz.Text = this.BytesToString(array3);
                    }
                    catch
                    {
                        MessageBox.Show("数据转换错误,请输入数字。", "错误");
                    }
                }
            }
        }

 

posted @ 2015-03-18 21:48  视觉℡  阅读(1106)  评论(0编辑  收藏  举报