educative.io

Bitwise operator

num1 = 10
num = 20
please explain the not function
print= (~num1)


Course: https://www.educative.io/courses/learn-python-3-from-scratch
Lesson: Bitwise Operators - Learn Python 3 from Scratch

Hi @Preeti_Kothiyal !!
In Python, the tilde symbol (~) is a bitwise operator that performs the bitwise complement operation on its operand. When we apply the ~ operator to a number, it flips the bits in its binary representation.

num1 = 10
num = 20
print= (~num1)

In the code, we have assigned the value 10 to the variable num1, and we are applying the ~ operator to it. The binary representation of 10 as a signed integer in two’s complement notation is 0b00001010 (assuming 8-bit representation), where the leftmost bit is the sign bit, with 0 indicating a positive number and 1 indicating a negative number. In two’s complement notation, the bitwise complement of a binary number is obtained by flipping all its bits and then adding 1. So the bitwise complement of 00001010 (which represents the signed integer -10 in two’s complement notation) would be:

00001010 (original binary representation of -10)

11110101 (flip all bits)

1111010 (add 1) (2’s complement of 10)
To convert a binary number in two’s complement notation to its decimal equivalent, we follow these steps:

  1. If the leftmost bit is 1, we know the number is negative. To find its magnitude, we take the bitwise complement of the binary number (i.e., flip all the bits) and add 1.
  2. If the leftmost bit is 0, the number is positive and we simply convert the rest of the bits to decimal form using the standard binary to decimal conversion method.
    In the case of 11110101, the leftmost bit is 1, indicating that the number is negative. To find its magnitude, we first take the bitwise complement of the number, which results in:
    11110101 (original binary representation)

    00001010 (flip all bits)
    We then add 1 to this value to obtain the magnitude of the two’s complement representation of the number, which is:
    00001011 (add 1 to flipped value)
    The decimal equivalent of this binary value is -11. Therefore, the binary value 11110101 represents the signed integer -11 in two’s complement notation.
    I hope it helps. Happy Learning :blush:
1 Like