当前位置:   article > 正文

C#编写汉字转换GB2312--UTF-8窗体应用程序,进行汉字编码_c# 中文进行utf-8编码

c# 中文进行utf-8编码

C#编写汉字转换GB2312--UTF-8窗体应用程序,进行汉字编码,原文代码是跟着杜洋工作室视频进行编写:注意窗体程序中需要在textbox中设置竖直下拉框

 

 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace _14显示汉字
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18. private void Form1_Load(object sender, EventArgs e)
  19. {
  20. }
  21. private byte[] StringToBytes(string TheString) //utf8编码转GB2132编码
  22. {
  23. Encoding FromEcoding = Encoding.GetEncoding("UTF-8"); //UTF8编码
  24. Encoding ToEcoding = Encoding.GetEncoding("gb2312"); //GB2312编码
  25. byte[] FromBytes = FromEcoding.GetBytes(TheString); //获取汉字UTF8字节序列
  26. byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, FromBytes); //转换为GB2132字节码
  27. return Tobytes; //返回
  28. }
  29. private string BytesToString(byte[] Bytes) //过程同上
  30. {
  31. string Mystring;
  32. Encoding FromEcoding = Encoding.GetEncoding("gb2312");
  33. Encoding ToEcoding = Encoding.GetEncoding("UTF-8");
  34. byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, Bytes);
  35. Mystring = ToEcoding.GetString(Tobytes); //得到的是UTF8字节码序列,需要转换为UTF8字符串
  36. return Mystring; //转换
  37. }
  38. private void button1_Click(object sender, EventArgs e)
  39. {
  40. byte[] StringsToByte = StringToBytes(textBox1.Text); //得到字符串的GB2132字节编码
  41. textBox2.Text = "";
  42. foreach (byte MyByte in StringsToByte) //遍历未知大小的数组
  43. {
  44. string Str = MyByte.ToString("x").ToUpper(); //转换为16进制大写字符串
  45. textBox2.Text += "0x" + (Str.Length == 1 ? "0" + Str : Str) + " "; //填写
  46. }
  47. }
  48. private void button2_Click(object sender, EventArgs e)
  49. {
  50. byte[] data = new byte[textBox3.Text.Length / 2];
  51. int i;
  52. try //如果此时用户输入字符串中含有非法字符(字母,汉字,符号等等,try,catch块可以捕捉并提示)
  53. {
  54. string buffer = textBox3.Text;
  55. buffer = buffer.Replace("0x", ""); //为了保证汉字转编码输出结果(0xXX)可以通用,所以程序允许输入0xXX(可以带空格),程序会将0x和空格自动去除
  56. buffer = buffer.Replace(" ", string.Empty);
  57. for (i = 0; i < buffer.Length / 2; i++) //转换偶数个
  58. {
  59. data[i] = Convert.ToByte(buffer.Substring(i * 2, 2), 16); //转换
  60. }
  61. textBox4.Text = BytesToString(data); //diaplay
  62. }
  63. catch
  64. {
  65. MessageBox.Show("数据转换错误,请输入数字。", "错误");
  66. }
  67. }
  68. }
  69. }

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号