Sm1
Sm1

Reputation: 570

Is bitwise NOT operator different for C and Python?

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?

Upvotes: 0

Views: 306

Answers (1)

chepner
chepner

Reputation: 531683

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

Upvotes: 1

Related Questions