[英]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.GetBytes
和Encoding.GetString
將string
轉換為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.