Home > Net >  Unpack 16-bit integer values from a 64-bit field in MATLAB
Unpack 16-bit integer values from a 64-bit field in MATLAB

Time:12-01

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?

CodePudding user response:

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.

  • Related