【问题标题】:C# representation of hex in byte array字节数组中十六进制的 C# 表示
【发布时间】:2014-10-13 02:47:38
【问题描述】:

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

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

协议发送 'ENQ' '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);

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

【问题讨论】:

  • 只需将0x 放在您的价值观前面。喜欢0x050x2C
  • @Donal 问题不在于将字符串转换为字节数组。

标签: c# hex bytearray


【解决方案1】:

根据您提供的示例,您的设备需要将数据编码为 ASCII。 0x30 = ASCII 中的“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);

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多