如何使用c语言中的位运算符来反转位
例如:
i/p: 10010101
o/p: 10101001
答案 0 :(得分:2)
如果它只是8位:
u_char in = 0x95;
u_char out = 0;
for (int i = 0; i < 8; ++i) {
out <<= 1;
out |= (in & 0x01);
in >>= 1;
}
或奖励积分:
u_char in = 0x95;
u_char out = in;
out = (out & 0xaa) >> 1 | (out & 0x55) << 1;
out = (out & 0xcc) >> 2 | (out & 0x33) << 2;
out = (out & 0xf0) >> 4 | (out & 0x0f) << 4;
弄清楚最后一个如何运作是读者的练习; - )
答案 1 :(得分:2)
Knuth在The Art of Computer Programming Vol 4A中有一个关于位反转的部分,按位技巧和技巧。
要以分而治之的方式反转32位数的位,他使用魔术常数
u0 = 1010101010101010,(从-1 /(2 + 1)
u1 = 0011001100110011,(从-1 /(4 + 1)
u2 = 0000111100001111,(从-1 /(16 + 1)
u3 = 0000000011111111,(从-1 /(256 + 1)
方法归功于Henry Warren Jr.,黑客高兴。
unsigned int u0 = 0x55555555;
x = (((x >> 1) & u0) | ((x & u0) << 1));
unsigned int u1 = 0x33333333;
x = (((x >> 2) & u1) | ((x & u1) << 2));
unsigned int u2 = 0x0f0f0f0f;
x = (((x >> 4) & u2) | ((x & u2) << 4));
unsigned int u3 = 0x00ff00ff;
x = (((x >> 8) & u3) | ((x & u3) << 8));
x = ((x >> 16) | (x << 16) mod 0x100000000); // reversed
16位和8位的情况留给读者练习。
答案 2 :(得分:0)
嗯,这可能不是最优雅的解决方案,但它是一个解决方案:
int reverseBits(int x) {
int res = 0;
int len = sizeof(x) * 8; // no of bits to reverse
int i, shift, mask;
for(i = 0; i < len; i++) {
mask = 1 << i; //which bit we are at
shift = len - 2*i - 1;
mask &= x;
mask = (shift > 0) ? mask << shift : mask >> -shift;
res |= mask; // mask the bit we work at at shift it to the left
}
return res;
}
在一张纸上测试它似乎有效:D
编辑:是的,这确实非常复杂。我不知道为什么,但我想找到一个没有触及输入的解决方案,所以这来自我的haead