Thread Subject: Faster way to do bit shuffling

Subject: Faster way to do bit shuffling

From: Tam Chu

Date: 13 Nov, 2009 01:38:02

Message: 1 of 3

I need a short program to perform bit shuffling by taking a 32 bit vector
and reducing it to two 16 bit vectors, one containing even, the other odd bits

The following code works but takes a long time

i = dec2bin(invec,32);
e = uint16(bin2dec(i(1:2:32)));
o = uint16(bin2dec(i(2:2:32)));

Any suggestions regarding speeding this up?

Thanks.
T.

Subject: Faster way to do bit shuffling

From: tristram.scott@ntlworld.com (Tristram Scott)

Date: 13 Nov, 2009 09:26:01

Message: 2 of 3

Tam Chu <tchu@vectrsystems.com> wrote:
> I need a short program to perform bit shuffling by taking a 32 bit vector
> and reducing it to two 16 bit vectors, one containing even, the other odd
bits
>
> The following code works but takes a long time
>
> i = dec2bin(invec,32);
> e = uint16(bin2dec(i(1:2:32)));
> o = uint16(bin2dec(i(2:2:32)));
>
> Any suggestions regarding speeding this up?
>
> Thanks.
> T.

Are you doing this one value at a time in a loop? You can vectorise:

>> x = floor(rand(100000,1)*2^32);
>> i = dec2bin(x);
>> e = uint16(bin2dec(i(:,1:2:end)));
>> o = uint16(bin2dec(i(:,2:2:end)));

If that isn't fast enough, something like this:

function [e,o] = eo(x)
%eo Return numbers extracted from even and odd bits.

n = 32;
e = zeros(size(x));
o = zeros(size(x));
for i = 1:(n/2)
k = 2^(2*i-1);
e = e + (bitand(x,k) / k) * 2^(i-1);
k = 2^(2*i-2);
o = o + (bitand(x,k) / k) * 2^(i-1);
end




--
Dr Tristram J. Scott
Energy Consultant

Subject: Faster way to do bit shuffling

From: Jan Simon

Date: 13 Nov, 2009 10:05:19

Message: 3 of 3

Dear Tam Chu!

> i = dec2bin(invec,32);
> e = uint16(bin2dec(i(1:2:32)));
> o = uint16(bin2dec(i(2:2:32)));

Take a look into DEC2BIN and BIN2DEC. The conversion to CHAR is not needed in you case, so you can simplify the calls, e.g.:
  bin = rem(floor(invec * pow2(-31:0)), 2);
  twos = pow2(31:-1:0);
  e = sum(bin(1:2:32) .* twos(ones(size(invec, 1), 1), 1:2:32, 2);
  o = sum(bin(2:2:32) .* twos(ones(size(invec, 1), 1), 2:2:32, 2);

Please debug this (written in the news-editor). POW2 is not really fast, perhaps 2.^X is faster, or even better pre-calculate the needed values.

If invec is large, BSXFUN might be faster than blowing up the variable [twos].

Good luck, Jan

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Tag Activity for This Thread
Tag Applied By Date/Time
bit shuffling Tam Chu 12 Nov, 2009 20:39:02
rssFeed for this Thread

Contact us at files@mathworks.com