【问题标题】:How to read bytes in c#如何在c#中读取字节
【发布时间】:2011-12-19 06:55:43
【问题描述】:

我正在尝试处理我的传入缓冲区并确保我在每次传输时都获得了所有 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: ");              
    }
}

【问题讨论】:

  • 我试图澄清我的答案(我最初误读了问题),但是:BytesToRead 仅指本地接收缓冲区;它不会告诉你什么是传入的。通常,BytesToRead 之类的主要用途是:如果您想决定是处理已经存在的数据还是阻塞(同步),还是执行BeginRead(异步)跨度>

标签: c# multithreading bluetooth serial-port


【解决方案1】:

此时您正在读取直到 本地接收缓冲区 (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

【讨论】:

  • 感谢马克的回复。我在尝试创建新的缓冲区 [125] 数组时收到错误消息。我需要任何特定的命名空间吗?
  • @fb69 哦!不,我需要更好的手指;应该读过new byte[125] - 修复
猜你喜欢
  • 2012-10-04
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 2021-07-16
  • 2012-04-15
  • 1970-01-01
相关资源
最近更新 更多