使用逐比特反转 [英] Bit Reversal using bitwise
问题描述
我试图做到位反转一个字节。我用下面
I am trying to do bit reversal in a byte. I use the code below
static int BitReversal(int n)
{
int u0 = 0x55555555; // 01010101010101010101010101010101
int u1 = 0x33333333; // 00110011001100110011001100110011
int u2 = 0x0F0F0F0F; // 00001111000011110000111100001111
int u3 = 0x00FF00FF; // 00000000111111110000000011111111
int u4 = 0x0000FFFF;
int x, y, z;
x = n;
y = (x >> 1) & u0;
z = (x & u0) << 1;
x = y | z;
y = (x >> 2) & u1;
z = (x & u1) << 2;
x = y | z;
y = (x >> 4) & u2;
z = (x & u2) << 4;
x = y | z;
y = (x >> 8) & u3;
z = (x & u3) << 8;
x = y | z;
y = (x >> 16) & u4;
z = (x & u4) << 16;
x = y | z;
return x;
}
有可反向的位(32位的计算机上),但有一个问题, 例如,该输入是10001111101,我想获得10111110001,但这种方法会扭转整个字节包括标题0。输出为10111110001000000000000000000000。 有没有什么方法来仅扭转实际数量?我不希望将其转换为字符串和反向,然后再进行转换。有没有纯粹的数学方法或位操作方法?
It can reverser the bit (on a 32-bit machine), but there is a problem, For example, the input is 10001111101, I want to get 10111110001, but this method would reverse the whole byte including the heading 0s. The output is 10111110001000000000000000000000. Is there any method to only reverse the actual number? I do not want to convert it to string and reverser, then convert again. Is there any pure math method or bit operation method?
最好的问候,
推荐答案
不好的方法是转移,直到你得到一个1右侧:
Cheesy way is to shift until you get a 1 on the right:
if (x != 0) {
while ((x & 1) == 0) {
x >>= 1;
}
}
请注意:您应该所有的变量切换到无符号整型
。正如写你可以有多余的符号扩展任何时候你右移。
Note: You should switch all the variables to unsigned int
. As written you can have unwanted sign-extension any time you right shift.
这篇关于使用逐比特反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!