Skip to content

Bitwise NOT operator in Python

  • by

Python Bitwise NOT operator is denoted by ~. It Returns one’s complement of the number. Bitwise operator normally working on bits(0’s and 1’s)

Bitwise NOT operator in Python

Simple example code inverts each bit from the binary representation of the integer x so that 0 becomes 1 and 1 becomes 0. This is semantically the same as calculating ~x == -x-1. For example, the bitwise NOT expression ~0 becomes -1, ~9 becomes -10, and ~32 becomes -33.

x = 0
print(~x)

x = 9
print(~x)

x = 32
print(~x)

Output:

Bitwise NOT operator in Python

Note: first the number is converted to binary and then processed.

Remember that the bitwise NOT operator operates on the binary representation of the number, and its behavior might be different depending on whether you’re using a signed or unsigned integer representation.

Do comment if you have any doubts or suggestions on this Python operator topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading