c#如何计算数据接收处理程序中接收的数据量?

时间:2014-08-25 03:29:31

标签: c#

我从串口接收数据(字节),现在我想在数据接收处理程序中写一个if else。

If(condition)
 {}
else
 {}

if的条件是:接收的字节数/ 8 =整数。 例如,我收到16个字节的数据,因此16/2 = 8,是一个整数。我收到了20个字节的数据,20/8 = 2.5,它不是整数。

 private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        byte[] b = new byte[800];
        int Received;
        SerialPort sp = (SerialPort)sender;
        if (condition)
        {
            MessageBox.Show("      Transmission error!");
        }
        else
        {
            Received = sp.Read(b,0,8);
        if (Received < 8) 
            return;
        float f11 = BitConverter.ToSingle(b, 0);
        float f22 = BitConverter.ToSingle(b, 4);
        Invoke(new Action(() =>
        {
          textBox3.Text += f11.ToString() + "    "+f22.ToString()+"\r\n";
          //MessageBox.Show("      New Message Received!");
        }));
        Received = 0;
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用% operator

if (number_of_bytes_received % 8 == 0)