正在从串行端口读取有符号整数

本文关键字:符号 整数 读取 串行端口 | 更新日期: 2023-09-27 17:58:37

我使用read方法一次从串行端口读取12个字节。我正在正确地接收字节形式的数据。然而,一旦我有了这些字节,我就试图将它们转换为有符号整数。字节的顺序是(最低有效字节1)、(最高有效字节1。

while ((intErg = serialPort1.Read(comBuffer, 0, comBuffer.Length)) > 0)
      {
          string strErg2 = "";          
          double vbatmsb = 0;
          double vbatlsb = 0;
          short imsb = 0;
          double vbattotal = 0.0;

          for (int i = 0; i < comBuffer.Length; i++)
          {
              switch (i)
              {
                  case 0:
                       imsb = (short)(comBuffer[i+1] << 8 + comBuffer[i]);
                       strErg2 += imsb.ToString()+ ", ";
                      break;                
                  case 2:
                       imsb = (short)(comBuffer[i+1] << 8 + comBuffer[i]);
                       strErg2 += imsb.ToString()+ ", ";
                      break;
                  case 4:
                       imsb = (short)(comBuffer[i+1] << 8 + comBuffer[i]);
                       strErg2 += imsb.ToString()+ ", ";
                      break;
                  case 6:
                      imsb = (short)(comBuffer[i] << 8 + comBuffer[i + 1]);
                       strErg2 += imsb.ToString()+ ", ";
                      break;                    
                  case 8:
                       imsb = (short)(comBuffer[i+1] << 8 + comBuffer[i]);
                       strErg2 += imsb.ToString()+ ", ";
                      break;
                  case 10:
                      vbatlsb = comBuffer[i];
                      break;
                  case 11:
                      strErg2 += ", ";
                      vbatmsb = comBuffer[i];
                      vbattotal = ((vbatmsb * 256.0 + vbatlsb) * 6.6) / 4095.0;
                      strErg2 += vbattotal.ToString();
                      break;
              }

          }
          this.BeginInvoke(new EventHandler(delegate
          {
              SetTheText(strErg2);
          }));
      }

comBuffer是由serialPort1.Read命令填充的字节数组。最后2个字节被区别对待,因为它们是无符号整数并且是正确的。然而,我试图重新组装成有符号整数的前10个字节甚至没有接近它们应该的值。有人建议我重新组装这些字节时做错了什么吗?

正在从串行端口读取有符号整数

使用BitConverter将字节数组转换为其他类型。类似的东西

while....
{
  if (comBufferLength >= 2)
  {
     imsb1 = BitConverter.ToInt16(comBuffer, 0);
     if (comBufferLength >= 4)
       imsb2 = BitConverter.ToInt16(comBuffer, 2);
       ....