当前位置:首页 > C# > c#汉字与编码之间的转换(输出十六进制)

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


除特别注明外,本站所有文章均为视觉电子科技原创,转载请注明出处来自https://feelsight.cn/post/6.html

赞 (0

发表评论

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

分享:

支付宝

微信