如何根据传入的读取字节设置字节大小

How to set a byte size according to incoming read bytes

我正在研究串口编程。我设置了如下缓冲区

byte[] buffer = new byte[4096];

现在,在阅读它时,我得到的字节数少于 4096。响应可能会有所不同,因此没有固定的接收字节数。请看下面

//read using a Stream
  port.BaseStream.Read(buffer, 0, (int)buffer.Length);

  var receiveData = BitConverter.ToString(buffer,0, buffer.Length);

输出

68-81-16-01-06-3D-4A-60-0B-86-E8-46-04-68-00-00-00-00-04-02-00-00-00-39-04-22-00-00-00-2E-04-42-00-00-00-39-04-00-00-00-00-00-04-20-00-00-00-00-04-40-00-00-00-00-02-06-00-00-02-26-00-00-02-46-00-00-4E-23-16-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-........-nn

如何将响应字节精确设置为其返回长度?

Read returns 一个整数,它存储了你的数组实际接收和使用了多少字节。您可以在 BitConverter.

中使用此值
int receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);

var receiveData = BitConverter.ToString(buffer,0, receivedBytes );