Search code examples
cbinarybit-manipulationbitwise-operators

How to swap pairs of bits of unsigned int in C


This is the code I have so far? But its not working..

uint64_t bit_swap(uint64_t value) {
    return ((value & 0xAAAAAAAA) >> 1) |
            ((value & 0x55555555) << 1);   
}

bit_swap(0x1111111111111111) should return 0x2222222222222222 but is returning 0x0000000022222222 instead


Solution

  • value & 0xAAAAAAAA
    

    That is equivalent to : value & 0x00000000AAAAAAAA

    And since we know that anything anded with 0 will give 0 hence the top 32 bits will always be 0. Change to:

    return ((value & 0xAAAAAAAAAAAAAAAA) >> 1) |
            ((value & 0x5555555555555555) << 1);