Skip to main content

Turn off the rightmost set bit

The "rightmost set bit" refers to the rightmost (or least significant) bit in a binary representation of a number that is equal to 1.

To turn off the rightmost set bit, you can use a bitwise operation. One common method is to use the bitwise AND operator (&) with the complement of a number that has only the rightmost set bit set to 1.

Turn off the rightmost active bit

Here's an example in Python:

n = 352   # binary representation: 101100000
n = n & (n-1)
print(n) # output: 320 (binary representation: 10100000)

In this example, n-1 results in a number that has all the bits to the right of the rightmost set bit set to 1, and the rightmost set bit itself set to 0. So the bitwise AND operation with n clears the rightmost set bit.

Note that if the input number has no set bits, the result of turning off the rightmost set bit will be zero.

Code Solution





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment