编程语言
首页 > 编程语言> > C#:串口通信下位机返回的高低位负数补码处理

C#:串口通信下位机返回的高低位负数补码处理

作者:互联网

1.处理读取的两位高低8位报文,整理为一个补码:bytesTest是这两位报文的数组
for (int i = 0; i < bytesTest.Length; i++)
{
  string strTemp = System.Convert.ToString(bytesTest[i], 2);
  strTemp = strTemp.Insert(0, new string('0', 8 - strTemp.Length));
  strResult += strTemp;
}
string first = strResult.Substring(0, 1);

2.对整理得到的补码还原得到无符号的整数值:
if (first == "1")
{
  strR = "0";
  for (int i = 1; i < strResult.Length; i++)
  {
    if (strResult.Substring(i, 1) == "0")
    {
      strR += "1";
    }
    else if (strResult.Substring(i, 1) == "1")
    {
      strR += "0";
    }
  }
  strResult = strR;
}
int iResult = Convert.ToInt32(strResult, 2);
return iResult;

标签:string,C#,strR,strResult,补码,int,strTemp,串口,bytesTest
来源: https://www.cnblogs.com/Hypocriser/p/14977731.html