sla*_*den 2 c# bit-manipulation
我知道这已经多次被问到类似的差异,但是我在 C#(Unity3D) 中按位运算的输出遇到了问题。
我正在尝试进行位反转排列,即为了在Cooley-Tukey FFT 算法中使用而获得整数(或无符号整数,任一)的位反转顺序。所以如果我有 0, 1, 2, 3 - 我想以 0, 2, 1, 3 结束,如果我有 0, 1, 2, 3, 4, 5, 6, 7 - 我应该得到 0, 4、2、6、1、5、3、7。
我尝试了一些在网上找到的位反转算法,例如这个:
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;
}
Run Code Online (Sandbox Code Playgroud)
我会像这样使用它:
uint x = 1;
x = ReverseBits(x); //this results in x = 2147483648;
Run Code Online (Sandbox Code Playgroud)
我想尝试另一种算法,所以我找到了这个算法,正如指出的那样反转字节:
public uint ReverseBytes(uint value)
{
return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 |
(value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24;
}
Run Code Online (Sandbox Code Playgroud)
我得到了完全相同的数字,x = 2147483648
。像>>
在 C# 中的按位运算符执行的功能与在其他语言(如 C)中的功能相同,对吗?那么,我错过了一步吗?
您当前使用的反向位的算法整个整数(对于即32位int
和64位long
),而你真正想要的是扭转只有第一个 k
位(其中n = 2^k
对位反向排列)。
一个简单的解决方案是使用字符串:
int x = 6;
int k = 3;
// Binary representation of x of length k
string binaryString = Convert.ToString(x, 2).PadLeft(k, '0');
int reversed = Convert.ToInt32(Reverse(binaryString), 2);
Run Code Online (Sandbox Code Playgroud)
其中Reverse
定义如下:
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想使用字符串,则可以坚持使用按位运算符解决方案:
int x = 6;
int k = 3;
int reversed = 0;
for(int i = 0; i < k; i++) {
// If the ith bit of x is toggled, toggle the ith bit from the right of reversed
reversed |= (x & (1 << i)) != 0 ? 1 << (k - 1 - i) : 0;
}
Run Code Online (Sandbox Code Playgroud)
您甚至可以以可读性为代价删除三元运算符:
reversed |= (((x & (1 << i)) >> i) & 1) << (k - 1 - i);
Run Code Online (Sandbox Code Playgroud)
在& 1
当右算术移位(为的情况下补偿>> i
)填充的符号位。