serial-port - C# WinForms。处理从串口接收到的十六进制数据。我做对了吗?
问题描述
我通过串行端口接收十六进制数组,然后从消息中提取最后一个字节,并对提取的字节和始终静态的字节执行“按位与”计算。
我的代码有效,但我想知道你们中的任何人是否会以另一种方式,也许是更清洁的方式?这是我的代码,欢迎批评和建设性意见:
byte[] messageOK = {0x00,0x55,0x02,0x19,0x41}; //This is a good message
byte[] message7f = {0x00,0x55,0x02,0x19,0x7f}; //This is another acceptable message
byte[] message1 = {0x00,0x55,0x02,0x19,0x01}; //This is considered a bad message
byte[] buffer;
int bitwise41 = Convert.ToInt32("0x41", 16); //BitwiseAND calculation result must always be 41
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytes = serialPort1.BytesToRead;
buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);
this.Invoke(new EventHandler(ShowData));
}
private void ShowData(object sender, EventArgs e)
{
tBoxDataIn.Text += BitConverter.ToString(buffer).Replace("-", " "); //Here I'm converting 'buffer' so entire message can be easily read in debug textbox as hex string
tBoxDataIn.AppendText(DateTime.Now.ToString("\thh:mm:ss"));
tBoxDataIn.AppendText(Environment.NewLine);
string toCompare = BitConverter.ToString(buffer).Replace("-", "").Remove(0,8); //Here I'm removing first 8 characters from the hex string, so I'm left with the byte I'm interested in for comparison
int intToCompare = Convert.ToInt32(toCompare, 16); //Converting my string into base-16 int
int bitwiseAndResult = bitwise41 & intToCompare; //Perform BitwiseAND calculation
if (bitwiseAndResult == 0x41) //If result is 41 test is passed, else test is failed
label1.Text = "PASS";
else
label1.Text = "FAIL";
label2.Text = "BITWISE-AND RESULT: " + bitwiseAndResult.ToString("X2"); //Display what the calculation result was
}
解决方案
推荐阅读
- java - 提示 = Keycloak 和 Spring Security Oauth2 之间的登录
- c# - Linq查询相交表中的多对多关系
- c# - 我的响应中的某些属性为 NULL,无法通过 Fiddler 跟踪请求
- c# - 为什么 DropDownList 返回错误的值?
- python - 安装 KIVY 时出错:为什么执行后出现错误:“python -m pip install kivy”?
- python - 如何在python中用上述值和以下值的平均值填充空值?
- python - 我的 updateView 创建一个新帖子而不是更新旧帖子
- php - 当时间到达指定日期时更改sql字段的值
- javascript - 如何使用 aws-serverless-express 和 lambda 上传文件?
- python - TKinter 条目的 Python 输出具有 Float64