문제

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