Turn off the rightmost bit of an integer

How will you turn off the rightmost bit in the binary representation of an unsigned int number.

Solution:

We have to turn off the right most bit in binary representation of a number. For example

Input:  18 (00…010010)
Output: 16 (00…010000)
Input:  15 (00…001111)
Output: 14 (00…001110)

The solution uses the fact that in the binary representation of (n-1)  all bits from right till x will be toggled, where x is the rightmost set bit in binary representation of n. For example:

n   = 18 (00…010010)
n-1 = 17 (00…010001)
n   = 15 (00…001111)
n-1 = 14 (00…001110)
n   = 8 (00…001000)
n-1 = 7 (00…000111)

If we want to turn off the rightmost set bit, then we just need to do a bit-wise AND of n & n-1.

    unsigned int turnOffRightMostSetBit(unsigned int n)
    {
        return n&(n-1);
    }

0 Comments

Leave a comment