简体   繁体   English

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

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

I am very new to C# and using VS, but need a little help. 我对C#和使用VS非常陌生,但需要一些帮助。

I have a textbox where a user can put in a value, for example "658" . 我有一个文本框,用户可以在其中输入一个值,例如"658" I want to convert this into bytes first (max 3 bytes) before sending it to the serialport. 我想convert this into bytes first (max 3 bytes)convert this into bytes first (max 3 bytes)然后再将其发送到串行端口。 So the first byte sent is 0x02 and the second byte sent is 0x92 . 因此,发送的第一个字节为0x02 ,发送的第二个字节为0x92

The second thing I am having issues with is the same but in reverse. 我遇到的第二件事是相同的,但相反。 I receive data in bytes, for example "0x0B, 0xC7, 0x14" and then I need to convert them into a decimal value and display them in a different Textbox. 我收到以字节for example "0x0B, 0xC7, 0x14"单位的数据, for example "0x0B, 0xC7, 0x14" ,然后我需要将它们转换为十进制值,并在不同的文本框中显示它们。

I have tried a number of conversions that did not seem to work (parse, Tobyte and even using binary converter) so I am in need of help. 我尝试了许多似乎无效的转换(解析,Tobyte甚至使用二进制转换器),因此我需要帮助。

Thanks 谢谢

This should get you started: 这应该使您开始:

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.

Convert From Bytes to Numeric: 从字节转换为数字:

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

Note, you want to pay attention to endian-ness. 注意,您要注意字节顺序。 See this: https://msdn.microsoft.com/en-us/library/bb384066.aspx 看到这个: https : //msdn.microsoft.com/en-us/library/bb384066.aspx

You can use Encoding.GetBytes and Encoding.GetString to convert string to byte[] and back. 您可以使用Encoding.GetBytesEncoding.GetStringstring转换为byte[]并返回。

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

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

That should no be a problem as both the sending and the receiving serial port will accept/return a byte array. 这应该没有问题,因为发送和接收串行端口都将接受/返回字节数组。 So the question comes down to how you create a by array from a string. 因此,问题归结为如何从字符串创建by数组。

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

The way back is: 返回的方式是:

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

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

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