首页 > 其他 > 详细

Reverse Bits

时间:2014-12-15 18:55:57      阅读:273      评论:0      收藏:0      [点我收藏+]

Reverse bits of an unsigned integer.

typedef unsigned int uint;

uint swapBits(uint x, uint i, uint j)
{
    uint lo = ((x >> j) & 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;
}

还有一些trick的方法,不再列出,可参考原网页:http://leetcode.com/2011/08/reverse-bits.html

Reverse Bits

原文:http://www.cnblogs.com/litao-tech/p/4165387.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!