如何在c#中读取字节

本文关键字:读取 字节 | 更新日期: 2023-09-27 18:18:27

我正在尝试处理传入缓冲区,并确保在每次传输时获得所有125字节的数据。我创建了一个字节数组。我怎么知道125字节的数据正在被接收。我试着显示字节数,但它显示不同的数字,我不确定它是否是正确的编码来获得接收的字节数。

下面是我的代码:

void datareceived(object sender, SerialDataReceivedEventArgs e)
{
    myDelegate d = new myDelegate(update);
    listBox1.Invoke(d, new object[] { });
}

public void update()
{
    Console.WriteLine("Number of bytes:" + serialPort.BytesToRead); // it shows 155
    while (serialPort.BytesToRead > 0)
        bBuffer.Add((byte)serialPort.ReadByte());         
    ProcessBuffer(bBuffer);
}
private void ProcessBuffer(List<byte> bBuffer)
{
    // Create a byte array buffer to hold the incoming data
    byte[] buffer = bBuffer.ToArray();
    // Show the user the incoming data // Display mode
    for (int i = 0; i < buffer.Length; i++)
    {
        listBox1.Items.Add("SP: " + (bBuffer[43].ToString()) + "  " + " HR: " + (bBuffer[103].ToString()) + " Time: ");              
    }
}

如何在c#中读取字节

此刻你正在读取,直到本地接收缓冲区 (BytesToRead)是空的,然而,一个更好的方法是保持一个缓冲区和偏移量,并循环,直到你有你需要的,即使这意味着等待-即

byte[] buffer = new byte[125]
int offset = 0, toRead = 125;
...
int read;
while(toRead > 0 && (read = serialPort.Read(buffer, offset, toRead)) > 0) {
    offset += read;
    toRead -= read;
}
if(toRead > 0) throw new EndOfStreamException();
// you now have all the data you requested