Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获得最高有效字节和较低有效字节的int/double?_C#_Unity3d_Garmin - Fatal编程技术网

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)时需要强制转换。