-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?

1
  • 3
    That comment you got, that code-translation is off-topic for Stack Overflow, was incorrect. Undeleting this. Nov 25, 2021 at 15:29

1 Answer 1

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.

3
  • Tested and works like charm. Thanks.
    – Power
    Nov 30, 2021 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, 2021 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. Dec 1, 2021 at 2:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.