How to invert alternate bits of a number
Posted
by
Cupidvogel
on Stack Overflow
See other posts from Stack Overflow
or by Cupidvogel
Published on 2012-10-27T07:10:25Z
Indexed on
2012/10/27
11:01 UTC
Read the original article
Hit count: 202
python
|bit-manipulation
The problem is how to invert alternate bits of a number, starting from the LSB
. Currently what I am doing is first doing a
count = -1
while n:
n >>= 1
count += 1
to first find the position of the leftmost set bit, then running a loop to invert every alternate bit:
i = 0
while i <= count:
num ^= 1<<i
i += 2
Is there a quick hack solution instead of this rather boring loop solution? Of course, the solution can't make any asumption about the size of the integer.
© Stack Overflow or respective owner