0

Bitwise not operator: Returns one’s compliment of the number in Python.

In C, bitwise not operator just flips the bits. So both the languages perform differently.

Q1: Is there an equivalent bit flip operation in Python

Q2: The one's complement of a number is usually the flipped operation. However, in the link for Python, the example includes the opposite sign followed by the result of adding 1 ie. ~x = ~(binary_x) = -(binary_x+1).

This operation based on my understanding is not equal to one's complement as in C. Rather, the not in Python looks similar to 2's complement.

So what is this operation and what is the correct way to do Bitwise NOT ~ in Python?

4
  • 1
    Because ints are of variable size in Python, the closest equivalent to "just flipping the bits" is -(x+1), which is what ~ does. If that isn't giving you the result you want, you should probably give more detail about what problem you're trying to solve. Commented Jun 24, 2021 at 22:06
  • 2
    You don't have to rely on geeks for geeks, Python has docs: docs.python.org/3/reference/…. With arbitrary precision integers, bit flipping doesn't make sense. Commented Jun 24, 2021 at 22:09
  • - in Python is subtraction. But Python integers are quite different from C integers at the bit level. Commented Jun 24, 2021 at 22:15
  • @Sm1 It's defined differently because ints in Python work differently from ints in C. But it's defined to be effectively similar. Commented Jun 24, 2021 at 22:29

1 Answer 1

1

Using the struct module, you can see that ~ does effectively flip the bits, when a fixed number of bits makes that interpretation meaningful.

An int in Python uses arbitrary precision, so all values are stored using the smallest number of 30-bit chunks necessary for the unsigned magnitude of the value, plus an explicit sign bit.

Here's an example that produces fixed-precision representations of 1 and ~1:

>>> struct.pack("!l", 1)
b'\x00\x00\x00\x01'
>>> struct.pack("!l", ~1)
b'\xff\xff\xff\xfe'

As you can see, ~1 is 1111 1111 1111 1111 1111 1111 1111 1110

Sign up to request clarification or add additional context in comments.

2 Comments

Is this operation similar to that of C or different? Is it only special to Python the way not is done?
It's similar, when the comparison makes sense. Python simply doesn't store integers in the same way C does.

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.