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.
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.
You can do it using bitmasks and bitshift in one step without breaking it into 4 different variables:
Go solution (try it on the Go Playground):
i := 0x9b // 10011011
fmt.Printf("%b
", i)
i = (i&0x03)<<6 | (i&0x0c)<<2 | (i&0x30)>>2 | (i&0xc0)>>6
fmt.Printf("%b
", i)
Output:
10011011
11100110
In Java:
int i = 0x9b; // 10011011
System.out.printf("%x
", i);
i = (i & 0x03) << 6 | (i & 0x0c) << 2 | (i & 0x30) >> 2 | (i & 0xc0) >> 6;
System.out.printf("%x
", i);
Output (it is hex, but represents the same numbers):
9b
e6
Since each bit-group (group of 2 bits) has to be moved from its original place in the input, I don't think you can do it in fewer steps (steps as masking and shifting). If this is not fast enough for you, your only option to make it faster is to pre-compute the transformation and store the results in an array as detailed in @ruakh's answer. Of course this becomes unfeasible if we allow more than just 8 bits.