首页 > 解决方案 > 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
}

标签: serial-porthexcomparisonbitwise-operators

解决方案


推荐阅读