文本框数据到字节,然后发送到串行端口&亦然

本文关键字:串行端口 亦然 然后 数据 到字节 文本 | 更新日期: 2023-09-27 18:03:13

我是c#和VS的新手,但需要一些帮助。

我有一个文本框,用户可以在其中输入一个值,例如"658"。我想在发送到串口之前先进行convert this into bytes first (max 3 bytes)。因此发送的第一个字节是0x02,发送的第二个字节是0x92

我遇到的第二件事是相同的,但相反。我接收数据在字节,for example "0x0B, 0xC7, 0x14",然后我需要将它们转换成一个十进制值,并显示在不同的文本框。

我已经尝试了一些似乎不工作的转换(解析,Tobyte甚至使用二进制转换器),所以我需要帮助。

谢谢

文本框数据到字节,然后发送到串行端口&亦然

这应该可以让你开始:

Convert From Numeric to Bytes:

var textInput = "658";
// validate...
var numericInput = Convert.ToInt32(textInput);
var convertedToBytes = BitConverter.GetBytes(numericInput);
// if your system is little endian (see below), reverse array output.

转换为数字:

// fourth octet is required to convert to an int32, which requires 4 bytes.
var bytesInput = new byte[] { 0x0, 0x0B, 0xC7, 0x14 }; 
// if your system is little endian (see below), reverse array.
var convertedFromBytes = BitConverter.ToInt32(bytesInput, 0);

注意,您需要注意尾序。参见:https://msdn.microsoft.com/en-us/library/bb384066.aspx

您可以使用Encoding.GetBytesEncoding.GetString来转换stringbyte[]

https://msdn.microsoft.com/ru-ru/library/ds4kkd55 (v = vs.110) . aspx

https://msdn.microsoft.com/ru-ru/library/744y86tc (v = vs.110) . aspx

这应该不是问题,因为发送和接收串行端口都将接受/返回字节数组。问题归结为如何从字符串创建一个by数组。

byte[] bytes = Encoding.ASCII.GetBytes(textBox1.Text);

回去的路是:

string s = Encoding.ASCII.GetString(bytes);