wener wener - 3 months ago 6
C Question

Fast way to switch bits order?

I have a binary like this

10011011


My data store like this
10,01,10,11
, but I want to reorder like this

11100110


The data look like
11,10,01,10
.This operation same as ByteOrder convert but in bits level.

Any fast bitop way to do this ?

Currently, I have to decode this to four int then merge to one.

Answer

The fastest way might be to precompute a table of all the values:

final int[] values = new int[256];
for (int i = 0; i < 256; ++i) {
    values[i] = (i & 0b1100_0000) >> 6
                | (i & 0b0011_0000) >> 2
                | (i & 0b0000_1100) << 2
                | (i & 0b0000_0011) << 6;
}

and then use array lookups rather than bit manipulation.

Naturally, you'll want to profile.