Search code examples
c++binarybitwise-operators

The fastest way to swap the two lowest bits in an unsigned int in C++


Assume that I have:

unsigned int x = 883621;

which in binary is :

00000000000011010111101110100101

I need the fastest way to swap the two lowest bits:

00000000000011010111101110100110

Note: To clarify: If x is 7 (0b111), the output should be still 7.


Solution

  • If you have few bytes of memory to spare, I would start with a lookup table:

    constexpr unsigned int table[]={0b00,0b10,0b01,0b11};
    
    unsigned int func(unsigned int x){
        auto y = (x & (~0b11)) |( table[x&0b11]);
        return y;  
    }
    

    Quickbench -O3 of all the answers so far.

    Quickbench -Ofast of all the answers so far.

    (Plus my ifelse naive idea.)

    [Feel free to add yourself and edit my answer].

    Please do correct me if you believe the benchmark is incorrect, I am not an expert in reading assembly. So hopefully volatile x prevented caching the result between loops.