Question: How to develop algorithm to shift all set bits (1) in 32-bits integer to the right
Example
V= 0b01001000110010
The V contains 5 set bits and if we shift them to the right we get:
V = 0b011111
What I have tried:
v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
The above code return the number of set bits in 32-bits integer
and with the following code
c = (1<<c) - 1;
we will get the c first bits set to 1. Explaination
Are there other algorithmes better than the above solution?
Is it possible to use only bitwise operations (&,|, ^, ~, >>, <<) in the proposed solutions?