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

我正在进行串行端口编程。我已经设置了如下的缓冲区

byte[] buffer = new byte[4096];

Now while reading it I am getting bytes less than 4096. The response may vary so there is no fix number of bytes received. Please see below

//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

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

评论
  • snihil
    snihil 回复

    Read returns an integer, which stores how many bytes are actually received and used by your array. You can use this value in your BitConverter.

    int receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
    
    var receiveData = BitConverter.ToString(buffer,0, receivedBytes );