汉字GB2312转码器
辅助以后单片机和12864oled的设计。
注意点:
- 汉字 转UTF-8 再转化为 GB2312
//字符转编码private byte[] StringToBytes(string TheString) //utf8编码转GB2132编码{Encoding FromEcoding = Encoding.GetEncoding(\"UTF-8\"); //UTF8编码Encoding ToEcoding = Encoding.GetEncoding(\"gb2312\"); //GB2312编码byte[] FromBytes = FromEcoding.GetBytes(TheString); //获取汉字UTF8字节序列byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, FromBytes); //转换为GB2132字节码return Tobytes; //返回}
//字符转编码private void button1_Click(object sender, EventArgs e) //转换按钮{byte[] StringsToByte = StringToBytes(textBox1.Text); //得到字符串的GB2132字节编码textBox2.Text = \"\";foreach (byte MyByte in StringsToByte) //遍历提取{string Str = MyByte.ToString(\"x\").ToUpper(); //转换为16进制大写字符串textBox2.Text += \"0x\" + (Str.Length == 1 ? \"0\" + Str : Str) + \" \"; //填写成0x** 格式}}
- GB2312 转为 UTF-8再转为 汉字
//编码转字符private string BytesToString(byte[] Bytes) //过程同上{string Mystring;Encoding FromEcoding = Encoding.GetEncoding(\"gb2312\");Encoding ToEcoding = Encoding.GetEncoding(\"UTF-8\");byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, Bytes);Mystring = ToEcoding.GetString(Tobytes); //得到的是UTF8字节码序列,需要转换为UTF8字符串return Mystring; //转换}
为了可以满足多种输入情况,提高软件的使用兼容性:
//编码转字符private void button2_Click(object sender, EventArgs e){byte[] data = new byte[textBox3.Text.Length / 2];int i;try //如果此时用户输入字符串中含有非法字符(字母,汉字,符号等等,try,catch块可以捕捉并提示){string buffer = textBox3.Text; //为了保证汉字转编码输出结果(0xXX)可以通用buffer = buffer.Replace(\"0x\", \"\"); //去掉0xbuffer = buffer.Replace(\" \", \"\"); //去掉空格for (i = 0; i < buffer.Length / 2; i++) //两个表示一位 转换偶数个{data[i] = Convert.ToByte(buffer.Substring(i * 2, 2), 16); //string转换为byte}textBox4.Text = BytesToString(data); //diaplay}catch{MessageBox.Show(\"数据转换错误,请输入数字。\", \"错误\");}}