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 长度
- reverse bit (!!!)
- Reverse Bit
- Bit Manipulation Reverse Bits
- [leetcode][bit] Reverse Bits
- Bit Manipulation - Reverse Bits
- Posts Tagged 【bit】Reverse Bits
- leetcode:Bit Manipulation:Reverse Bits(190)
- 复杂度Θ(log(n))的bit-wise reverse
- Bit Manipulation-----190. Reverse Bits&&191. Number of 1 Bits
- Reverse the bit in a integer 倒置整形数的bit
- Bit-map(转载)
- 树状数组(BIT)
- 树状数组(BIT)
- 树状数组(BIT)
- bit
- Bit++
- bit
- BIT
- VC++动态链接库(DLL)编程(zz)
- [Leetcode] Simplify Path
- Python Tkinter开发Symfony命令辅助工具
- Python web.py十分钟创建简易博客
- 最有效的window7 64位 安装方式 总结
- reverse bit (!!!)
- XPath
- 开始怀念博客了,又想再开始写了,继续写... ...
- 大数取余
- Python 生成pyc文件
- Oracle 11g R2 for Win7旗舰版(64位)的安装步骤
- web前端学习博客
- ie6、ie7下JSON.parse JSON未定义的解决方法
- Com学习