简体   繁体   English

如何在 Octave 中将两个 8 位数字组合为 16 位

[英]How to combine two 8-bit numbers to 16-bit in Octave

I'm working on the data from a GY-87 (acc and gyro sensor module), The data I have received from it is of the form ACCEL_YOUT_HIGH & ACCEL_YOUT_LOW for the Y axis specifying the HIGH and the LOW value respectively.我正在处理来自 GY-87(acc 和陀螺仪传感器模块)的数据,我从它收到的数据的格式为 ACCEL_YOUT_HIGH 和 ACCEL_YOUT_LOW,Y 轴分别指定 HIGH 和 LOW 值。 I've been told that "High and Low registers are 8-bit in nature, therefore the combination of both will be a 16-bit signed data".有人告诉我“高和低寄存器本质上是 8 位的,因此两者的组合将是 16 位有符号数据”。 But I really can't figure out how to combine them to 16 bit data.但我真的不知道如何将它们组合成 16 位数据。 Here is a sample: ACCEL_YOUT_HIGH=254 ACCEL_YOUT_LOW=144这是一个示例:ACCEL_YOUT_HIGH=254 ACCEL_YOUT_LOW=144

I've already tried the JAVAScript way, but its not working in octave.我已经尝试过 JAVAScript 方式,但它不能以八度音程工作。

var number8Bit1 = firstNumber & 0xff;
var number8Bit2 = ((firstNumber >> 8) & 0xff);

Since your data is 16-bit signed, I think the most elegant solution, is using typecast (as Andy commented).由于您的数据是 16 位签名的,我认为最优雅的解决方案是使用类型转换(正如安迪评论的那样)。

For typecast solution to work correctly you cad to do the following:为了使 typecast 解决方案正常工作,您 cad 执行以下操作:

  1. Cast each value to uint8将每个值转换为uint8
  2. Build an array from the two uint8 elements (put the lower element first, because our systems are little-endian )从两个uint8元素构建一个数组(将较低的元素放在第一位,因为我们的系统是little-endian
  3. Use typecast for converting the two bytes to single int16 element.使用类型转换将两个字节typecast为单个int16元素。
  4. Cast the result to double (you can skip this part, but it's a common practice - in case you need to apply computations to result).将结果转换为double (您可以跳过这部分,但这是一种常见做法 - 以防您需要对结果应用计算)。

Code sample:代码示例:

high = 254;
low = 144; 
res = double(typecast([uint8(low), uint8(high)], 'int16'))

Result:结果:

res = -368

In case you want to use pure mathematical operations (as Sami commented), you can do it as following:如果您想使用纯数学运算(如 Sami 评论的那样),您可以按以下方式进行:

res = high*256 + low;
if (res >= 2^15)
    res = res - 2^16; %Correct the sign.
end

I find it less elegant, because the if statement is unclear...我觉得它不太优雅,因为if语句不清楚......


You can also use bitshift , bitor and typecast (as Cris commented).您还可以使用bitshiftbitortypecast (正如 Cris 评论的那样)。
It looks like the C code res = (short)((high << 8) | low) :它看起来像 C 代码res = (short)((high << 8) | low)

res = typecast(uint16(bitor(bitshift(high, 8), low)), 'int16');

I find it less elegant than the first solution because shift and or operations are not natural in MATLAB / Octave...我发现它不如第一个解决方案优雅,因为移位和/或操作在 MATLAB / Octave 中并不自然......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM