-1

I am reading data from an accelerometer, which provides the measurements for each of the 3 axes (x, y, and z) as 16-bit integers packed into a single 64-bit field.

I have the following code in C to extract these 3 axis values:

uint8_t byte0 = *somevalue*, byte1 = *somevalue*, byte2 = *somevalue*, byte3 = *somevalue*, byte4 = *somevalue*, byte5 = *somevalue*;
uint64_t xyzDataReg = ((uint64_t) byte0<<40) + ((uint64_t) byte1<<32) + ((uint64_t) byte2<<24) + ((uint64_t) byte3<<16) + ((uint64_t) byte4<<8) + (uint64_t)byte5;
int16_t xRaw = (int16_t)((xyzDataReg >> 32) & 0xFFFF);
int16_t yRaw = (int16_t)((xyzDataReg >> 16) & 0xFFFF);
int16_t zRaw = (int16_t)(xyzDataReg & 0xFFFF);

But now I need to convert this code into MATLAB. How do I write these bit manipulation operations in MATLAB?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Power
  • 91
  • 8

1 Answers1

2

There are two approaches:

  1. Translate the code directly, using bitshift and bitand.

  2. Use typecast on the 64-bit array to convert it to a 16-bit array, then read out the values by indexing:

    a = uint64(1234567890);
    a = typecast(a, 'int16');
    x = a(3);
    y = a(2);
    z = a(1);
    

    Note that the order of the elements depends on the endianness of your architecture.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • Tested and works like charm. Thanks. – Power Nov 30 '21 at 14:36
  • For the first approach: `nth_byte = 1; % First uint16 byte dec2bin(bitand(bitshift(xyzDataReg,16*(1-nth_byte)),255));` – Power Nov 30 '21 at 14:37
  • Note that on earlier versions of MATLAB the typecast( ) call will result in a deep copy of the data, affecting performance. On later versions of MATLAB the typecast( ) call will result in a shared data copy, so performance will be good. – James Tursa Dec 01 '21 at 02:18