1

我使用 read 方法一次从串行端口读取 12 个字节。我正在正确接收字节形式的数据。但是,一旦我拥有这些字节,我就会尝试将它们转换为有符号整数。字节的顺序是(最低有效字节 1)、(最高有效字节 1)、(最低有效字节 2)、(最高有效字节 2)等。然后我尝试使用每个重新组装它们。

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 个字节甚至不接近它们应该是的值。当我重新组装这些时,有人对我做错了什么有什么建议吗?

4

1 回答 1

0

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

while....
{
  if (comBufferLength >= 2)
  {
     imsb1 = BitConverter.ToInt16(comBuffer, 0);
     if (comBufferLength >= 4)
       imsb2 = BitConverter.ToInt16(comBuffer, 2);
       ....
于 2013-02-22T18:38:19.777 回答