翻转无符号整数的比特位

给定一个无符号整数,要求将该整数的比特位按照高低位翻转。


typedef unsigned int uint;

uint swapbits(uint x, uint i, uint j)
{
    uint low = (x >> i)&1;
    uint high = (x >> j)&1;
    if (low != high)
    {
        x ^= (1U << j) | (1U << i);
    }

    return x;
}

uint revert(uint x)
{
    unsigned n = sizeof(x)*8;
    for (int i = 0; i < n/2; i++)
    {
        x = swapbits(x, i, n-1-i);
    }

    return x;
}


你可能感兴趣的:(翻转无符号整数的比特位)