版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/u012319493/article/details/82556939
dictScan:http://chenzhenianqing.com/articles/1101.html#comment-46945
摘自 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
unsigned long mask = ~0;
while ((s >>= 1) > 0)
{
// 将二进制位平均分成 sizeof(v) / s 组
mask ^= (mask << s); // mask:每组的低s位置1,高s位置0
v = ((v >> s) & mask) | ((v << s) & ~mask); // v:每组中的低s位与高s位交换
}
return v;
}
验证
#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <vector>
using namespace std;
void print2(int a[32])
{
for(int i=31; i>=0; i--)
{
cout << a[i];
if(i<31 && (i)%4 == 0)
cout << " ";
}
cout << endl;
}
void to2(int a[32], unsigned long x)
{
int i = 0;
while(x != 0)
{
a[i++] = x % 2;
x = x / 2 ;
}
print2(a);
}
unsigned long rev(unsigned long v)
{
int a[32];
unsigned long s = 8 * sizeof(v); // bit size; must be power of 2
unsigned long mask = ~0;
cout << "sizeof(v)\t\t" << sizeof(v) << endl;
cout << "s\t\t\t" << s << endl;
memset(a, 0, sizeof(a));
cout << "s\t\t\t";
to2(a, s);
memset(a, 0, sizeof(a));
cout << "mask\t\t\t";
to2(a, mask);
cout << endl;
while ((s >>= 1) > 0)
{
memset(a, 0, sizeof(a));
cout << "s\t\t\t";
to2(a, s);
memset(a, 0, sizeof(a));
cout << "mask\t\t\t";
to2(a, mask);
memset(a, 0, sizeof(a));
cout << "t = mask << s\t\t";
to2(a, mask << s);
mask ^= (mask << s);
memset(a, 0, sizeof(a));
cout << "mask ^= t\t\t";
to2(a, mask);
memset(a, 0, sizeof(a));
cout << "v1 = v >> s\t\t";
to2(a, v >> s);
memset(a, 0, sizeof(a));
cout << "v11 = v1 & mask\t\t";
to2(a, (v >> s) & mask);
memset(a, 0, sizeof(a));
cout << "v2 = v << s\t\t";
to2(a, v << s);
memset(a, 0, sizeof(a));
cout << "v22=v2&~mask\t\t";
to2(a, (v << s) & ~mask);
v = ((v >> s) & mask) | ((v << s) & ~mask);
cout << "v = v11|v22\t\t";
memset(a, 0, sizeof(a));
to2(a, v);
cout << endl;
}
return v;
}
int main()
{
int a[32];
memset(a, 0, sizeof(a));
int v = 0x32100123;
cout << "v\t\t\t" << v << endl;
cout << "v\t\t\t";
to2(a, v);
memset(a, 0, sizeof(a));
unsigned long ans = rev(v);
cout << "ans\t\t\t";
to2(a, ans);
return 0;
}