C++代码说明

Joh*_*Dow 0 c++ bitwise-operators

我有串行读取的数组,命名sensor_buffer.它包含21个字节.

gyro_out_X=((sensor_buffer[1]<<8)+sensor_buffer[2]);
gyro_out_Y=((sensor_buffer[3]<<8)+sensor_buffer[4]);
gyro_out_Z=((sensor_buffer[5]<<8)+sensor_buffer[6]);
acc_out_X=((sensor_buffer[7]<<8)+sensor_buffer[8]);
acc_out_Y=((sensor_buffer[9]<<8)+sensor_buffer[10]);
acc_out_Z=((sensor_buffer[11]<<8)+sensor_buffer[12]);
HMC_xo=((sensor_buffer[13]<<8)+sensor_buffer[14]);
HMC_yo=((sensor_buffer[15]<<8)+sensor_buffer[16]);
HMC_zo=((sensor_buffer[17]<<8)+sensor_buffer[18]);
adc_pressure=(((long)sensor_buffer[19]<<16)+(sensor_buffer[20]<<8)+sensor_buffer[21]);
Run Code Online (Sandbox Code Playgroud)

这行是做什么的:

variable = (array_var<<8) + next_array_var
Run Code Online (Sandbox Code Playgroud)

它对8位有什么影响?

<<8  ?
Run Code Online (Sandbox Code Playgroud)

更新:用另一种语言(java,处理)的任何例子?

处理示例:(为什么使用H像标题?).

/*
 * ReceiveBinaryData_P
 *
 * portIndex must be set to the port connected to the Arduino
 */
import processing.serial.*;

Serial myPort;        // Create object from Serial class
short portIndex = 1;  // select the com port, 0 is the first port

char HEADER = 'H';
int value1, value2;         // Data received from the serial port

void setup()
{
  size(600, 600);
  // Open whatever serial port is connected to Arduino.
  String portName = Serial.list()[portIndex];
  println(Serial.list());
  println(" Connecting to -> " + Serial.list()[portIndex]);
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  // read the header and two binary *(16 bit) integers:
  if ( myPort.available() >= 5)  // If at least 5 bytes are available,
  {
    if( myPort.read() == HEADER) // is this the header
    {
      value1 = myPort.read();                 // read the least significant byte
      value1 =  myPort.read() * 256 + value1; // add the most significant byte

      value2 = myPort.read();                 // read the least significant byte
      value2 =  myPort.read() * 256 + value2; // add the most significant byte

      println("Message received: " + value1 + "," + value2);
    }
  }
  background(255);             // Set background to white
  fill(0);                     // set fill to black
// draw rectangle with coordinates based on the integers received from Arduino
  rect(0, 0, value1,value2);
}
Run Code Online (Sandbox Code Playgroud)

mah*_*mah 10

您的代码具有相同的模式:

value = (partial_value << 8) | (other_partial_value)
Run Code Online (Sandbox Code Playgroud)

您的数组具有以8位字节存储的数据,但值为16位字节.每个数据点都是两个字节,最重要的字节首先存储在数组中.该模式通过将最高有效字节8位向左移位,然后将最低有效字节移位到低8位,简单地构建完整的16位值.