十六进制在字节数组中的c#表示

本文关键字:表示 数组 字节 字节数 十六进制 | 更新日期: 2023-09-27 18:18:55

我想通过串口发送十六进制值。

设备手册显示数据应该是这样的:

<>之前协议发送"询问"' 0 ' ' 0 ' ' 3 ' ',' ' 0 ' ' 0 ' ' 0 ' ' ETX '十六进制05 30 30 33 2C 30 30 30 03之前

代码:

<>之前 _serial.BaudRate = 9600; _serial.Parity = Parity.None; _serial.DataBits = 8; _serial.StopBits = StopBits.One; _serial.Open(); byte[] bytesToSend = new byte[9] { 05,30, 30, 33 , 2C , 30 , 30 , 30 , 03 }; // This should be represent bytes equivalent to hex value _serial.Write(bytesToSend,0,9); 之前

我知道我应该使用字节数组发送这个,但我不知道如何在数据字节数组中表示十六进制值

十六进制在字节数组中的c#表示

根据您提供的示例,您的设备需要将数据编码为ASCII。0x30 = '0'

正如其他人所说,您使用'0x'来表示十六进制值。

表示以ENQ开始以ETX结束的通用消息:

ASCIIEncoding asciiEncoding = new ASCIIEncoding();
string msg= "003,000";
byte[] msgBytes = asciiEncoding.GetBytes(msg);
byte[] bytesToSend = new byte[msgBytes.Length +2];
bytesToSend[0] = 0x05;
bytesToSend[bytesToSend.Length -1] = 0x03;
Buffer.BlockCopy(msgBytes, 0, bytesToSend, 1, msgBytes.Length);