Home > Back-end >  Extract bit range from byte array and create a new int
Extract bit range from byte array and create a new int

Time:01-06

I need to extract bits from a byte array (little endian), and then form a new int from it.

Say my byte array is this:

[0b00011001, 0b11001001, 0b00101010, 0b11001110]

And I need to extract bits 14 to 18 (inclusive).

First I bitmask like so:

[0b00011001, 0b11000000, 0b00000010, 0b11001110] using & 0b11000000 on [1] and & 0b00000111 on [2]

Then remove first byte, and reset other bytes:

[0b11000000, 0b00000010, 0b00000000, 0b00000000]

If I form an uint 32 out of this, it results in 704. Is this correct?

Is assuming MSB = 7 and LSB = 0 correct?

CodePudding user response:

As mentioned in the comments, it would be much easier to work with a union.

#include <stdio.h>
#include <stddef.h>

typedef union {
    uint32_t i;
    uint8_t c[4];
} u_t;

int main( void ) {
    u_t u = { 0 };

    // Little Endian machine
    u.c[0] = 0x19; // I believe these are the hex equivalent of OP data.
    u.c[1] = 0xC9;
    u.c[2] = 0x2A;
    u.c[3] = 0xCE;

    u.i &= 0x1F << (14-1); // Mask for 5 bits, b14-b18

    printf( "X\n", u.i );
    printf( "%u\n", u.i );

    printf( "%u\n", u.i >> 8 ); // my (our) mistake

    printf( "%u\n", u.i >> 14 ); // Perhaps what was intended

    return 0;
}
0002C000
180224
704
11

Of course, this would be much simpler just shifting the value to the right to begin with, then mask for the 5 lowest bits... C'est la guerre...

  • Related