
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is Tilde Operator in Python
In Python, the bitwise operator ~ (pronounced as tilde) is a complement operator. It takes one bit operand and returns its complement. If the operand is 1, it returns 0, and if it is 0, it returns 1.
For example, consider the 4-bit binary number (1100)2. By performing the tilde operation, each bit is flipped and results in (0011)2.
Tilde Operation on Decimal Numbers
When we perform a tilde operation on decimal numbers, the following steps are involved:
- Convert the decimal number to binary, including the sign. If the number is positive, place 0 in the MSB (Most Significant Bit); if it is negative, place 1 in the MSB.
- Perform the tilde operation (bitwise NOT), which flips all bits of the binary number.
- Convert the resulting binary number back to decimal. While doing this, consider the MSB as the sign bit (negative if it's 1, positive if it's 0).
Example
In the following example, we perform the tilde operation on the decimal number 5 by following the steps outlined above.
- The 4-bit binary representation of 5 is 0101. Since the number is positive, the MSB (most significant bit) is 0.
- Apply the tilde operation by flipping all the bits: 0101 → 1010.
- Convert 1010 back to decimal using two's complement interpretation:
-23 X 1 + 22 X 0 + 21 X 1 + 20 X 0 = -8 + 0 + 2 + 0 = -6
var1=5 print("Binary code of 5:",bin(var1)[2:]) #binary format of var1 excluding 0b tilde_res = ~(var1) #tilde operation on var1 print("Tilde operation on 5:",tilde_res)
Following is the output of the above code -
Binary code of 5: 101 Tilde operation on 5: -6
Using Tilde Operator with Boolean
In Python, when we apply the tilde operation on the boolean, it might work a bit differently, as True is considered as 1 and False is considered as 0.
Example
In the following example, we perform the tilde operation on Boolean values. Since True == 1 and False == 0, we apply bitwise NOT (~) to those integer values.
The binary representation of 1 (True) is 01, and for 0 (False), it is 00. When we apply the tilde operator (~), it flips all the bits -
- ~1 → 10 → -21 X 1 + 20 X 0 = -2
- ~0 → 11 → -21 X 1 + 20 X 1 = -1
The 1 in the MSB (most significant bit) indicates a negative number in two's complement form, while 0 indicates a positive number. So, the tilde operation on booleans in Python results in -2 for True and -1 for False.
print("The tilde operation on True:", ~True) #tilde operation on True print("The tilde operation on False:", ~False) #tilde operation on False
Following is the output of the above code -
The tilde operation on True: -2 The tilde operation on False: -1