Convert Raw 14 bit Two's Complement to Signed 16 bit Integer

后端 未结 5 927
一向
一向 2021-01-17 14:08

I am doing some work in embedded C with an accelerometer that returns data as a 14 bit 2\'s complement number. I am storing this result directly into a uint16_t

5条回答
  •  不要未来只要你来
    2021-01-17 15:01

    Assuming when code reaches return ((int32_t)raw_signed ..., it has a value in the [-8192 ... +8191] range:

    If RAW_SCALE_FACTOR is a multiple of 4 then a little savings can be had.

    So rather than

    int16_t raw_signed = raw << 2; 
    raw_signed >>= 2;
    

    instead

    int16_t fxls8471qr1_convert_raw_accel_to_mag(uint16_t raw,enum fxls8471qr1_fs_range range){
      int16_t raw_signed = raw << 2;
      uint16_t divisor;
      ...
      // return ((int32_t)raw_signed * RAW_SCALE_FACTOR) / divisor;
      return ((int32_t)raw_signed * (RAW_SCALE_FACTOR/4)) / divisor;
    }
    

提交回复
热议问题