• C#:串口显示汉字的程序设计


    1. 效果

    2. 代码

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace 汉字显示
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
            }
    
         // 工具类: 将汉字串转化为字节数组 (1个汉字 = 2个字节)
    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 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; //转换 }
         // 当用户点击(汉字[UTF-8格式]->编码[GB2312格式])转换时
    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) + " "; //填写 } }
    // 当用户点击(编码->汉字)转换时
    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; buffer = buffer.Replace("0x", ""); //为了保证汉字转编码输出结果(0xXX)可以通用,所以程序允许输入0xXX(可以带空格),程序会将0x和空格自动去除 buffer = buffer.Replace(" ", string.Empty); for (i = 0; i < buffer.Length / 2; i++) //转换偶数个 { data[i] = Convert.ToByte(buffer.Substring(i * 2, 2), 16); //转换 } textBox4.Text = BytesToString(data); //diaplay } catch { MessageBox.Show("数据转换错误,请输入数字。", "错误"); } } } }
  • 相关阅读:
    多线程总结三:控制线程
    ios -- 为导航栏添加播放动画
    IOS -- UITableView里面点击一个cell改变其他cell的设置
    IOS -- UICollectionView里面的cell点击,点击一个cell改变其他cell的状态
    ios -- Masonry 更新约束
    IOS--按钮里面 左边文字右边图片的设置
    IOS--时间 NSDate,NSTimeInterval的一些转换
    IOS--通过宽度算高度
    iOS App中添加半透明新手指引
    IOS--解决tableview里面cell 文本输入框键盘遮盖的问题
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/16317530.html
Copyright © 2020-2023  润新知