I know this has been asked in similar variances many times, but I'm having trouble with the output of bitwise operations in C#(Unity3D).
I'm trying to do bit-reversal permutation, that is, get the bit-reversed order of integers(or unsigned int, either one) for the purpose using in the Cooley-Tukey FFT algorithm. So if I have 0, 1, 2, 3 - I want to end up with 0, 2, 1, 3 and if I have 0, 1, 2, 3, 4, 5, 6, 7 - I should get 0, 4, 2, 6, 1, 5, 3, 7.
I've tried a few bit-reversal algorithms found online, such as this one:
public uint ReverseBits(uint n)
{
n = (n >> 1) & 0x55555555 | (n << 1) & 0xaaaaaaaa;
n = (n >> 2) & 0x33333333 | (n << 2) & 0xcccccccc;
n = (n >> 4) & 0x0f0f0f0f | (n << 4) & 0xf0f0f0f0;
n = (n >> 8) & 0x00ff00ff | (n << 8) & 0xff00ff00;
n = (n >> 16) & 0x0000ffff | (n << 16) & 0xffff0000;
return n;
}
And I'd use it like this:
uint x = 1;
x = ReverseBits(x); //this results in x = 2147483648;
I wanted to try another algorithm so I found this one, which as pointed out reverses the bytes:
public uint ReverseBytes(uint value)
{
return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 |
(value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24;
}
and I get the exact same number, x = 2147483648
. A bitwise operator such as >>
performs the same function in C# as it would in other languages such as C, right? So, am I missing a step?