c ByteToHexStr

本文介绍了一个简单的 C 语言函数,该函数能够将输入的字节数组转换为对应的十六进制字符串表示形式。通过使用字符数组和位操作实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

void ByteToHexStr(char* str, char* dest, int len)
{
	byte tmp;
	char stb[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
	for (size_t i = 0; i < len; i++)
	{
		tmp = dest[i];
		str[i * 2] = stb[tmp >> 4];
		str[i * 2 + 1] = stb[tmp & 15];
	}
	return;
}

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO.Ports; using System.IO; namespace 自制串口助手 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } #region 变量定义 bool m_p = true; //判断串口是否打开,布尔变量,用于判断串口是否已经打开 SerialPort serialport = new SerialPort(); //创建串口类的对象 public static string comDate = null; //接收串口数据并解析 private string receivedData = ""; // 新增:用于保存所有接收到的数据 #endregion /// <summary> /// 初始化窗体 /// </summary> private void Form1_Load(object sender, EventArgs e) { //设置窗口号com1 this.comboBox1.SelectedIndex = 0; //设置波特率 this.comboBox2.SelectedIndex = 0; //设置数据位8 this.comboBox3.SelectedIndex = 1; //设置校验位none this.comboBox4.SelectedIndex = 0; //设置停止位1 this.comboBox5.SelectedIndex = 0; } /// <summary> /// 打开/关闭串口 /// </summary> private void button1_Click(object sender, EventArgs e) { Openport();//调用 Openport() 方法 } private void Openport() { if (m_p == true) // 如果串口未打开,设置串口参数并打开串口 { this.button1.Text = "关闭串口";//更改按钮文本为“关闭串口 serialport.PortName = this.comboBox1.Text; //设置串口号 serialport.BaudRate = int.Parse(this.comboBox2.Text); //设置波特率 serialport.DataBits = int.Parse(this.comboBox3.Text); //设置数据位 serialport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.Text); // 添加校验位设置 serialport.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox4.Text); serialport.Open(); //打开串口 serialport.DataReceived += new SerialDataReceivedEventHandler(Serialport_Datareceived); m_p = false;//更新串口状态为已打开 } else//如果串口已打开,则关闭串口并更新按钮文本和状态 { this.button1.Text = "打开串口";//更改按钮文本为“打开串口” serialport.Close();// 关闭串口 m_p = true;// 更新串口状态为未打开 } } /// <summary> /// 接收数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Serialport_Datareceived(object sender, SerialDataReceivedEventArgs e) { //将byte数组转成字符串显示出来 int count = serialport.BytesToRead; byte[] recive = new byte[count]; // 创建字节数组以存储接收到的数据 //读取数据 serialport.Read(recive, 0, count); //判断转换成字符还是16进制 if (this.radioButton1.Checked) //字符串 { string strRecieve = Encoding.Default.GetString(recive); // 将字节数组转换为字符串 Control.CheckForIllegalCrossThreadCalls = false; //避免线程占用 if (checkBox1.Checked) { textBox1.AppendText(strRecieve + "\r\n"); } else { this.textBox1.Text += strRecieve; } receivedData += strRecieve; // 追加到总数据中 } if (this.radioButton2.Checked) //16进制 { string hexData = byteTohexstr(recive); if (checkBox1.Checked) { // 使用Invoke方法安全地更新UI this.Invoke(new MethodInvoker(() => { textBox1.Text += hexData + "\r\n"; })); } else { this.Invoke(new MethodInvoker(() => { textBox1.Text += hexData; })); } receivedData += hexData; // 追加到总数据中 comDate = hexData; ExtractData(); //提取串口数据 } } //将字节数组转换为16进制字符串。 public static string byteTohexstr(byte[] bytes) { string str = ""; //构建返回字符串 if (bytes != null) { for (int i = 0; i < bytes.Length; i++) //循环转化成字符串 { str += bytes[i].ToString("x2") + ""; } } return str; } //将接收到的16进制字符串数据提取并转换为整数数组 public static void ExtractData() { int[] intArray = { }; string[] strArray = { }; strArray = comDate.Split(); //提取返回数据到数组中 strArray = strArray.Take(strArray.Count() - 1).ToArray(); //从数组中删除最后一项 for (int i = 0; i < strArray.Length; i++) { try { intArray[i] = Convert.ToInt32(strArray[i]); } catch (Exception) { // 捕获转换异常 } } } /// <summary> /// 发送数据 /// </summary> private void button2_Click(object sender, EventArgs e) { try { // 将文本框中的字符串转换为字节数组 if (radioButton2.Checked) //十六进制 { // 将文本框中的字符串转换为字节数组 byte[] d = strTohexByte(this.textBox2.Text); serialport.Write(d, 0, d.Length); } if (radioButton1.Checked) //字符串发送 { byte[] SendBuf = new byte[1024 * 1024]; SendBuf = Encoding.Default.GetBytes(this.textBox2.Text); serialport.Write(SendBuf, 0, SendBuf.Length); } } catch (Exception) { } } private byte[] strTohexByte(string HEXstring) //字符串转化16进制 { HEXstring = HEXstring.Replace(" ", ""); if ((HEXstring.Length % 2) != 0) { HEXstring += " "; } byte[] returnbytes = new byte[HEXstring.Length / 2]; for (int i = 0; i < returnbytes.Length; i++) { returnbytes[i] = Convert.ToByte(HEXstring.Substring(i * 2, 2).Replace(" ", ""), 16); } return returnbytes; } /// <summary> /// 清空数据 /// </summary> private void button3_Click(object sender, EventArgs e) { this.textBox1.Text = ""; } /// <summary> /// 保存所有收到的数据到指定文件 /// </summary> private void button4_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(receivedData)) { MessageBox.Show("没有可保存的数据!"); return; } if (saveFileDialog1.ShowDialog() == DialogResult.OK) { try { File.WriteAllText(saveFileDialog1.FileName, receivedData); MessageBox.Show("数据已成功保存到:" + saveFileDialog1.FileName); } catch (Exception ex) { MessageBox.Show("保存失败:" + ex.Message); } } } } }写出每一段注释并且让我知道这个代码的用处,并且画出流程图
最新发布
06-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值