DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 4: Bitwise Operators and Ternary Operator

Bitwise XOR (^)

XOR stands for Exclusive OR.

The result is 1 when both bits are different. If both bits are the same, the result is 0.

a b a ^ b
True True False
True False True
False True True
False False False

Example:

print(4 ^ 5)  # 1
Enter fullscreen mode Exit fullscreen mode

Binary calculation:

4 = 100

5 = 101

XOR = 001 = 1

Binary 001 means:
(0 * 4) + (0 * 2) + (1 * 1) = 1

Another example:


no1, no2 = 5, 5

print(no1 ^ no2)  # 0
Enter fullscreen mode Exit fullscreen mode

Because both numbers are the same, the XOR result is 0.

Bitwise NOT (~)

The Bitwise NOT operator reverses the bits of a number.

In Python, the result of Bitwise NOT can be calculated using this formula:

~n = -(n + 1)

Examples:


print(~4)   # -5
print(~5)   # -6
print(~6)   # -7

print(~0)   # -1
print(~-1)  # 0
Enter fullscreen mode Exit fullscreen mode

Let's understand how it works:

~4 = -(4 + 1)

= -5

Shift Operators

Shift operators are used to move the bits of a number to the left or right.

Python has two shift operators:

  • << Left Shift
  • >> Right Shift

Left Shift (<<)

The left shift operator moves the bits towards the left. For positive integers, each shift by one position multiplies the number by 2.

print(4 << 1)  # 8
print(4 << 2)  # 16
print(4 << 3)  # 32
Enter fullscreen mode Exit fullscreen mode

Right Shift (>>)

The right shift operator moves the bits towards the right. For positive integers, each shift by one position divides the number by 2 and takes the floor value.

print(4 >> 1)  # 2
print(4 >> 2)  # 1
Enter fullscreen mode Exit fullscreen mode

Ternary Operator (Conditional Expression)

The ternary operator is also called the conditional expression in Python.

It allows us to write a simple if-else condition in a single line.

Syntax:

value_if_true if condition else value_if_false

Example:

no1, no2 = 10, 20

result = 100 if no1 > no2 else 200

print(result)  # 200
Enter fullscreen mode Exit fullscreen mode
no1, no2, no3 = 1000, 200, 30

bigger_value = (
    no3 if no3 > no2 and no3 > no1
    else no2 if no2 > no3 and no2 > no1
    else no1
)

print(bigger_value)  # 1000
Enter fullscreen mode Exit fullscreen mode

Top comments (0)