What is the fastest way to perform the following bit-wise transformation?

X..XA01..1 // input
X..X011..1 // output

Thus the least significant zero bit has to be set to one, and the bit left to it (regardless it is zero or one) has to be set to zero, and that's it.

有帮助吗?

解决方案

Getting the rightmost zero is easy: ~x & (x + 1)

Using that, you can do this in a couple of easy steps: (not tested)

uint32_t rightmost_zero = ~x & (x + 1);
uint32_t result = (x | rightmost_zero) & ~(rightmost_zero << 1);

There may be a simpler/faster way.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top