For a FFT function I need to permutate or shuffle the elements within an array in a bit-reversed way. That's a common task with FFTs because most power of two sized FFT functions either expect or return their data in a bit-reversed way.
E.g. assume that the array has 256 elements I'd like to swap each element with it's bit-reversed pattern. Here are two examples (in binary):
Element 00000001b should be swapped with element 10000000b
Element 00010111b should be swapped with element 11101000b
and so on.
Any idea how to do this fast and more important: in-place?
I already have a function that does this swap. It's not hard to write one. Since this is such a common operation in DSP I have the feeling that there are more clever ways to do it than my very naiive loop.
Language in question is C, but any language is fine.
FFT and IFFT Blocks Data Order The FFT block enables you to output the frequency indices in linear or bit-reversed order. Because linear ordering of the frequency indices requires a bit-reversal operation, the FFT block may run more quickly when the output frequencies are in bit-reversed order.
Given an integer, reverse its bits using binary operators. For example, -100 in binary is 11111111111111111111111110011100 . On reversing its bits, we get number 973078527 which is 00111001111111111111111111111111 in binary.
“Bit reversal” is just what it sounds like: reversing the bits in a binary word from left to right. Therefore the MSBs become LSBs and the LSBs become MSBs.
To swap in place with a single pass, iterate once through all elements in increasing index. Perform a swap only if the index is less-than the reversed index -- this will skip the double swap problem and also palindrome cases (elements 00000000b, 10000001b, 10100101b) which inverse to the same value and no swap is required.
// Let data[256] be your element array
for (i=0; i<256; i++)
j = bit_reverse(i);
if (i < j)
{
swap(data[i],data[j]);
}
The bit_reverse() can be using Nathaneil's bit-operations trick. The bit_reverse() will be called 256 times but the swap() will be called less than 128 times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With