C# 如何获得最高有效字节和较低有效字节的int/double?
我从速度传感器获取这些字节:C# 如何获得最高有效字节和较低有效字节的int/double?,c#,unity3d,garmin,C#,Unity3d,Garmin,我从速度传感器获取这些字节: byte[] array = new byte[2]; array[0] = response.getDataPayload()[6]; array[1] = response.getDataPayload()[7]; 第一个是MSB(最高有效字节),第二个是LSB(较低有效字节)。我知道这一点,因为这是它在文档中说的 如何将这两个变量转换为int/double?(在c#)中如果需要将所有字节转换为正数,请尝试以下方法: int value = arra
byte[] array = new byte[2];
array[0] = response.getDataPayload()[6];
array[1] = response.getDataPayload()[7];
第一个是MSB(最高有效字节),第二个是LSB(较低有效字节)。我知道这一点,因为这是它在文档中说的
如何将这两个变量转换为int/double?(在c#)中如果需要将所有字节转换为正数,请尝试以下方法:
int value = array[1]*256 + array[0];
有一个名为的内置类,它只执行以下操作:
byte[] array = new byte[2];
array[0] = response.getDataPayload()[7];
array[1] = response.getDataPayload()[6];
//or, you could do:
array[0] = response.getDataPayload()[6];
array[1] = response.getDataPayLoad()[7];
Array.Reverse(array);
//end-or
short myVar = BitConverter.ToInt16(array, 0);
int myInt = (int)myVar;
double myDouble = (double)myVar;
因为2字节是一个短的(16位整数),这就是你从传感器中得到的。然后,如果需要,可以将其转换为完整的32位整数或双精度整数
字节交换为尾数。使用Convert.ToInt32方法-查看位转换器类
int result=((int)数组[0])也关闭,但提示错误,0x0100不关闭255@BenVoigt非常迂腐的AdamF建议“尝试”代码,但从未声称这是正确的解决方案:)最好交换填充数组的方式,位转换器
是little-endian。谢谢,更正@Benvoigt只是品味的问题,但对我来说,int-myInt=(int)myVar;double myDouble=(double)myVar代码>看起来过于明确。我会使用intmyint=myVar;double-myDouble=myVar代码>,或var myInt=(int)myVar;var myDouble=(double)myVar代码>。当然,生成的字节码是相同的。它是冗长的,我个人不会在实践中这样做,但它表明变量可以更改为其他类型。这里100%不需要强制转换,但在使用无法隐式转换的类型(如double到float)时需要强制转换。