I want to know how to implement the following Java code into its Python equivalent.
In Java, I am taking a number and using bitwise operators clearing the bits from some index through to the 0th index(inclusive)
int clearBitsIthrough0(int num, int i) {
int mask = (-1 << (i + 1));
return num & mask;
}
My attempt at the equivalent python code is below
def clearBitsIThrough0(num, i):
mask = format(0xf << 4, 'b')
return num & mask
However, I get a
TypeError: unsupported operand type(s) for &: 'int' and 'str'
I know this happens because mask is a string here, but if I convert it to an int, I lose the underlying integer value and I still get the wrong result.
I tried it a different way doing the following
def clearBitsIThrough0(num, i):
mask = int(format(0xf << 4, 'b'), 2)
num = int(format(num, 'b'), 2)
print(num, mask)
return num & mask
But this returns 0, which is the wrong answer.
How do I do this?