Last Updated
Viewed 1,112,871 Times

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

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

# Similar Question 1 : Bit manipulation to convert leftmost set bits to right-side alternating bits?

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` 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.

# Similar Question 3 : Change a bit of an integer [duplicate]

We have an integer number

``````int x = 50;
``````

in binary, it's

``````00110010
``````

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

cc