Redis二进制反转算法分析

```/* Function to reverse bits. Algorithm from:
* http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel */
static unsigned long rev(unsigned long v) {
unsigned long s = 8 * sizeof(v); // bit size; must be power of 2, 此处为32
unsigned long mask = ~0;  //11111111111111111111111111111111
while ((s >>= 1) > 0) {  //循环5次
// 左移s位并保留低位，右移s位并保留高位，然后两部分或运算
// 这里是实现移位的精华所在，结合下面打印信息有助于理解
v = ((v >> s) & mask) | ((v << s) & ~mask);
}
return v;
}```

```#include <iostream>

using namespace std;

// 打印二进制
void printBits(const unsigned long v) {
unsigned long mask = 1 << 31;
int bit = (v & mask) ? 1 : 0;
cout << bit;
}
cout << endl;
}

static unsigned long rev_test(unsigned long v) {
unsigned long s = 8 * sizeof(v); // bit size; must be power of 2
cout << "s      : ";
printBits(s);

while ((s >>= 1) > 0) {
cout << endl;
cout << "s      : ";
printBits(s);
v = ((v >> s) & mask) | ((v << s) & ~mask);
cout << "v      : ";
printBits(v);
}

return v;
}

int main() {
unsigned long v = 8;
cout << "v      : ";
printBits(v);
cout << endl;
v = rev_test(v);
cout << endl;
cout << "v      : ";
printBits(v);

cout << endl << endl << endl;

system("pause");
return 0;
}```

运行上述程序结果如下：