Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 762
Mojtaba Valizadeh Avatar asked Oct 28 '21 10:10

Mojtaba Valizadeh


1 Answers

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.

like image 136
Quimby Avatar answered Oct 11 '22 02:10

Quimby