2

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?

1 Answer 1

2

The same code works in Python:

def clearBitsIThrough0(num, i):
    mask = (-1 << (i + 1))
    return num & mask
Sign up to request clarification or add additional context in comments.

2 Comments

Just tried it myself. I was just stupid not to try that. I didn't try it because I figured since -1 in Python is not represented as 1111 (which it is in Java), this wouldn't work. Should I just delete the question, since it doesn't seem to serve any purpose?
There is value in showing that high-level Python also lets you do low-level bitstuff!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.