Last Updated
Viewed 1,112,871 Times

How do you set, clear, and toggle a bit?

I'm trying to maximally optimize a low-level subroutine, but I can't figure out the fastest way to flip the bits in this specific case:

Given a binary integer n wherein all set bits are to the left of all clear bits (e.g. 11110000, 110000, 1110000), is it possible to produce a resulting binary integer of digit length ((number of set bits in n) - 2) * 2, with all even bits set and all odd bits clear?

Example:

n = 111000, answer: 10
n = 1111000, answer: 1010
n = 110, answer: 0
n = 111110000000, answer: 101010
n = 1111111111000000000, answer: 1010101010101010

n is guaranteed to have at least 2 set bits, and at least (set bits - 1) clear bits

The answer must utilize only a constant number of bit manipulation and/or arithmetic operations (i.e. loopless), and can't use any type conversions (integers only, no strings).

Similar Question 2 : add and remove last bit

I am trying to determine the next and previous even number with bitwise operations.

So for example for the next function:

x    nextEven(x)
1       2
2       2
3       4
4       4

and for the previous:

x    previousEven(x)
1       0
2       2
3       2
4       4

I had the idea for the nextEven function something like: value = ((value+1)>>1)<<1;

And for the previousEven function something like: value = ((value)>>1)<<1

is there a better approach?, without comparing and seeing if the values are even or odd.

Thank you.

This question already has an answer here:

We have an integer number

int x = 50;

in binary, it's

00110010

How can I change the fourth (4th) bit programatically?

Similar Question 4 (3 solutions) : ERROR in understanding bit-wise operations

Similar Question 7 (4 solutions) : By Left shifting, can a number be set to ZERO

Similar Question 9 (1 solutions) : What does bitwise operation n&(n-1) do?

cc