Removing first bit

c++, python

Solution

There's a bit twiddling hack to remove a bit at a time until only the uppermost is left:

def upper_bit(x):
    while x & (x - 1):
        x &= x - 1
    return x

Now you can use that as a mask:

def mask_off(x, mask):
    return x & ~mask

>>> mask_off(6, upper_bit(6))
2

Note that this only works for positive numbers, because of the boundless nature of Python ints.

Problem

Is there an efficient way to remove the first bit of a number in C++ / Python, assuming you don't know how large the number is or its datatype? I know in Python I can do it by getting the bin(n), truncating the string by 1, and then recasting it to an int, but I am curious if there is a more "mathematical" way to do this. e.g. say the number is 6, which is 110 in binary. Chop the first bit and it becomes 10, or 2.

Original source

Related problems