繁体   English   中英

将文本框数据转换为字节,然后发送到串行端口,反之亦然

[英]Textbox data to Byte then sent to serialport & vice versa

我对C#和使用VS非常陌生,但需要一些帮助。

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

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

我尝试了许多似乎无效的转换(解析,Tobyte甚至使用二进制转换器),因此我需要帮助。

谢谢

这应该使您开始:

从数字转换为字节:

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.GetStringstring转换为byte[]并返回。

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM