Efficient shuffling bits of a binary vector

I recorded data containing a vector of bit sequences, which I would like to organize again. One value in a data vector might look like this:

bit0, bit1, bit2, ... bit7 

I would like to reorder this sequence of bits in the following order:

 bit0, bit7, bit1, bit6, bit2, bit5, bit3, bit4 

If I had only one value, this could work with:

 sum(uint32(bitset(0,1:8,bitget(uint32(X), [1 8 2 7 3 6 4 5])))) 

Unfortunately, bits and bit rate are not able to process bit sequence vectors. Since I have a fairly large dataset, I'm interested in efficient solutions.

Any help would be appreciated, thanks!

+5
source share
3 answers

dec2bin and bin2dec can process vectors, you can enter all numbers at the same time and rearrange the matrix:

 input=1:23; pattern = [1 8 2 7 3 6 4 5]; bit=dec2bin(input(:),numel(pattern)); if size(bit,2)>numel(pattern) warning('input numbers to large for pattern, leading bits will be cut off') end output=bin2dec(bit(:,pattern)); 

if available, I would use de2bi and bi2de .

+3
source

I don’t know if I can ask the question incorrectly, but can it not be resolved by indexing wrapped in cellfun ?

 %// example data BIN{1} = dec2bin(84,8) BIN{2} = dec2bin(42,8) %// pattern and reordering pattern = [1 8 2 7 3 6 4 5]; output = cellfun(@(x) x(pattern), BIN, 'uni', 0) 

Or what is the format of the input and the desired output?


 BIN = '01010100' '00101010' output = '00100110' '00011001' 
+1
source

The most efficient way is to use bitget and bitset , as in your question, although you only need an 8-bit integer. Suppose you have an uint8 X array that describes your recorded data (example below, X = uint8([169;5]) ) for no particular reason. We can check the bits by creating a useful anonymous function:

 >> dispbits = @(W) arrayfun(@(X) disp(bitget(X,1:8)),W) >> dispbits = @(W)arrayfun(@(X)disp(bitget(X,1:8)),W) >> dispbits(X) 1 0 0 1 0 1 0 1 1 0 1 0 0 0 0 0 

and suppose you have a pattern , according to which you want to change the order of the bits stored in this integer vector:

 >> pattern pattern = 1 8 2 7 3 6 4 5 

You can use arrayfun and find to change the bit order according to pattern :

 Y = arrayfun(@(X) uint8(sum(bitset(uint8(0),find(bitget(X,pattern))))), X) Y = 99 17 

We get the required answer, effectively stored in a vector of 8-bit integers:

 >> class(Y) ans = uint8 >> dispbits(Y) 1 1 0 0 0 1 1 0 1 0 0 0 1 0 0 0 
0
source

All Articles