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

时间:2014-08-19 21:05:20

标签: c# hex bytearray

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

设备手册显示数据应如下所示:

Protocol sent ’ENQ’ ’0’ ’0’ ’3’ ’,’ ’0’ ’0’ ’0’ ’ETX’        
Hexadecimal    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);


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

1 个答案:

答案 0 :(得分:1)

根据您提供的示例,您的设备需要以ASCII编码的数据。 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);
相关问题