reverse bit (!!!)

来源:互联网 发布:牢不可破的联盟知乎 编辑:程序博客网 时间:2024/06/05 14:50

如果只是reverse一个integer 可以由两种方法

1. 两个bit交换

typedef unsigned int uint;uint swapBits(uint x, uint i, uint j) {  uint lo = ((x >> i) & 1);  uint hi = ((x >> j) & 1);  if (lo ^ hi) {    x ^= ((1U << i) | (1U << j));  }  return x;} uint reverseXor(uint x) {  uint n = sizeof(x) * 8;  for (uint i = 0; i < n/2; i++) {    x = swapBits(x, i, n-i-1);  }  return x;}
注意要写成 1U

2. 二分法

 Let us use an example of n == 8 (one byte) to see how this works:

      01101001    /         \   0110      1001  /   \     /   \ 01   10   10   01 /\   /\   /\   /\0 1  1 0  1 0  0 1

The first step is to swap all odd and even bits. After that swap consecutive pairs of bits, and so on…
Therefore, only a total of log(n) operations are necessary.

uint reverseMask(uint x) {  assert(sizeof(x) == 4); // special case: only works for 4 bytes (32 bits).  x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);  x = ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2);  x = ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4);  x = ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8);  x = ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16);  return x;}

如果要reverse很多integer,可以用上述方法再加hash查表,表的大小为2^n, n为unsigned int的bit 长度