Discussion:
How to do bit reversal in Matlab?
(too old to reply)
Kevin
2006-11-25 05:33:10 UTC
Permalink
Is there a fast way (or vectorized code) of doing bit reversal in
Matlab?

For example, if number of bits is 4, then bit reversal of 1 is 8.

This problem can get tricky when the number of bits is large (eg.
40). Doing any math with such a big number can lead to precision
problem?

I know that I can use BITGET and BITSET. But I am wondering if there
is a better way.

Thanks.
Roger Stafford
2006-11-25 06:20:27 UTC
Permalink
Post by Kevin
Is there a fast way (or vectorized code) of doing bit reversal in
Matlab?
For example, if number of bits is 4, then bit reversal of 1 is 8.
This problem can get tricky when the number of bits is large (eg.
40). Doing any math with such a big number can lead to precision
problem?
I know that I can use BITGET and BITSET. But I am wondering if there
is a better way.
Thanks.
-------------------
If you're using double precision floating point ('double') numbers which
are integers, you can do this:

dr = bin2dec(fliplr(dec2bin(d,n))); % Bits in dr are in reverse order

where n is the number of bits to be reversed and where 0 <= d < 2^n.

You will experience no precision problems at all as long as the integers
are no more than 52 bits long.

Roger Stafford
Rune Allnor
2006-11-25 12:24:20 UTC
Permalink
Post by Kevin
Is there a fast way (or vectorized code) of doing bit reversal in
Matlab?
For example, if number of bits is 4, then bit reversal of 1 is 8.
This problem can get tricky when the number of bits is large (eg.
40). Doing any math with such a big number can lead to precision
problem?
I know that I can use BITGET and BITSET. But I am wondering if there
is a better way.
Probably not. Bit manipulations are very low-level operations that
ought to be done in assembly code. Using any high-level language
only adds overhead.

If you REALLY want to do this yourself, write a C MEX file where
you run through a list of numbers and berform the operation.
You will want to look at the << and >> operators in C:

http://www.phim.unibe.ch/comp_doc/c_manual/C/CONCEPT/bit_shift.html

Rune
d***@hotmail.com
2006-11-25 13:53:54 UTC
Permalink
Post by Kevin
Is there a fast way (or vectorized code) of doing bit reversal in
Matlab?
For example, if number of bits is 4, then bit reversal of 1 is 8.
This problem can get tricky when the number of bits is large (eg.
40). Doing any math with such a big number can lead to precision
problem?
I know that I can use BITGET and BITSET. But I am wondering if there
is a better way.
Thanks.
How large will the numbers be that you need to reverse? May I ask what
is the purpose of it? Maybe there is a more efficient way to solve the
whole problem. If the numbers are large you can just store the bits as
a string. To reverse it just read the string backwards! Or use
fliplr().

Daniel

Loading...