标签:
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
uint32_t reverseBits(uint32_t n) { long output = 0; int count = 0; //记录第几位 while(n) { while(pow(2.0, count) <= n) //找到不大于n的最大count count++; output += pow(2.0, 32 - count); //当pow(2.0, count) > n时,count需要减一才是目标count n -= pow(2.0, count - 1); //因为要反转,所以31 - (count - 1) count = 0; } return output; }
uint32_t reverseBits(uint32_t n) { unsigned int answer; unsigned int i; answer = 0; /*把一个unsigned int 数字1一直左移,直到它变成全0的时候,也就得到了该机器内unsigned int的长度*/ for (i = 1; i != 0; i <<= 1) { answer <<= 1; if (n & 1) { answer |= 1; } //如果n & 1不是0的话才把answer的最后位置1 n >>= 1; } return answer; }
标签:
原文地址:http://www.cnblogs.com/dylqt/p/4941597.html