从串口读取有符号整数

时间:2013-02-11 17:35:06

标签: c# integer serial-port 16-bit

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

1 个答案:

答案 0 :(得分:0)

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

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