Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep every n-th bits and collapse them in the least significant bits

I have a 32 bits integer that I treat as a bitfield. I'm interested in the value of the bits with an index of the form 3n where n range from 0 to 6 (every third bit between 0 and 18) I'm not interested in the bits with index in the form 3n+1 or 3n+2.

I can easily use the bitwise AND operator to keep the bits i'm interested in and set all the others bits to zero.

I would also need to "pack" the bits I'm interested in in the 7 least significant bits positions. So the bit at position 0 stay at 0, but the bit at position 3 is moved to position 1, the bit at position 6 moves to position 2 and so on.

I would like to do this in an efficient way, ideally without using a loop. Is there a combinations of operations I could apply to an integer to achieve this?

Since we're only talking about integer arithmetics here, I don't think the programming language I plan to use is of importance. But if you need to know :

I'm gonna use JavaScript.

like image 213
Mathieu Pagé Avatar asked Sep 12 '25 04:09

Mathieu Pagé


1 Answers

If the order of the bits is not important, they can be packed into bits 0-6 like this:

function packbits(a)
{
    // mask out the bits we're not interested in:
    var b = a & 299593; // 1001001001001001001 in binary
    // pack into the lower 7 bits:
    return (b | (b >> 8) | (b >> 13)) & 127;
}

If the initial bit ordering is like this:

bit 31                         bit 0
xxxxxxxxxxxxxGxxFxxExxDxxCxxBxxA

Then the packed ordering is like this:

bit 7  bit 0
0CGEBFDA
like image 57
samgak Avatar answered Sep 14 '25 00:09

samgak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!