Back to Python
2026-01-138 min read

Example of Python Bitwise Operators

Learn Example of Python Bitwise Operators step by step with clear examples and exercises.

Title: Mastering Python Bitwise Operators: An In-depth Guide

Why This Matters

In this tutorial, we will delve deep into the fascinating world of bitwise operators in Python. Understanding these operators is crucial for several reasons:

  1. Efficiency: Bitwise operations can be faster than their equivalent arithmetic counterparts, especially when dealing with large numbers or binary data. This speedup can lead to significant performance improvements in certain applications.
  2. Interviews and Exams: Knowledge of bitwise operators is often tested in coding interviews and competitive programming exams. Familiarizing yourself with these operators will help you tackle complex problems more effectively.
  3. Real-world Applications: Bitwise operators are used extensively in various areas like cryptography, game development, and system programming. They enable efficient manipulation of individual bits within an integer, which can lead to smaller memory footprints and faster execution times in certain scenarios.

Prerequisites

Before diving into the core concept of bitwise operators, ensure you have a solid understanding of the following:

  1. Basic Python Syntax (variables, data types, control structures)
  2. Arithmetic Operators (addition, subtraction, multiplication, division, modulus)
  3. Conditional Statements (if-else, elif)
  4. Loops (for, while)
  5. Functions and Modules
  6. Error Handling (try-except blocks)
  7. Understanding of the binary number system and its conversion to/from decimal and hexadecimal representations.
  8. Familiarity with the concept of least significant bit (LSB) and most significant bit (MSB).

Core Concept

Bitwise operators manipulate individual bits within an integer. Each integer is represented in binary format, where each digit (0 or 1) corresponds to a power of 2 from right to left. For example, the decimal number 13 can be represented as 1101 in binary.

Python provides the following bitwise operators:

  • Bitwise AND: & - Produces 1 only when corresponding bits are both 1. Example: 5 & 7 = 4 (binary representation: 101 & 0111 = 0100)
  • Bitwise OR: | - Produces 1 when at least one of the corresponding bits is 1. Example: 5 | 7 = 11 (binary representation: 101 | 0111 = 111)
  • Bitwise XOR: ^ - Produces 1 when exactly one of the corresponding bits is 1. Example: 5 ^ 7 = 6 (binary representation: 101 ^ 0111 = 110)
  • Bitwise NOT: ~ - Flips all the bits in an integer. Example: ~5 = -6 (binary representation: 1011 flipped becomes 1100)
  • Left Shift: << - Moves the bits to the left by a specified number of places, filling vacated positions with zeros. Example: 5 << 2 = 20 (binary representation: 101 shifted left by 2 becomes 10100)
  • Right Shift: >> - Moves the bits to the right by a specified number of places, filling vacated positions with zeros or the sign bit for negative numbers. Example: 5 >> 2 = 1 (binary representation: 101 shifted right by 2 becomes 001)

Bitwise AND and Least Significant Bit (LSB)

One common use case of the bitwise AND operator is checking the least significant bit (LSB) of a number. To check the LSB, we can use bitwise AND with a number that has a 1 in the desired position and zeros everywhere else. Shifting this number by 1 ensures that only the LSB is checked. For example: n & 1 checks the LSB of n.

Bitwise Operations on Negative Numbers

When performing bitwise operations on negative numbers, it's important to remember that Python uses two's complement representation for negative integers. This means that the bits are flipped and then one is added to the result. For example, the binary representation of -5 is 1011, which corresponds to ~5 + 1.

Worked Example

Let's consider an example to better understand these operators:

a = 60 # binary: 1111000
b = 13 # binary: 01101
c = a & b # Bitwise AND
print(f"{c} (binary: {bin(c)[2:]})") # Output: 12 (binary: 00001100)
d = a | b # Bitwise OR
print(f"{d} (binary: {bin(d)[2:]})") # Output: 61 (binary: 1110001)
e = a ^ b # Bitwise XOR
print(f"{e} (binary: {bin(e)[2:]})") # Output: 49 (binary: 1010001)
f = ~a # Bitwise NOT
print(f"{f} (binary: {bin(f)[2:]})") # Output: -61 (binary: 10001100)
g = a << 2 # Left Shift
print(f"{g} (binary: {bin(g)[2:]})") # Output: 240 (binary: 11110000)
h = a >> 2 # Right Shift
print(f"{h} (binary: {bin(h)[2:]})") # Output: 15 (binary: 00001111)

In this example, we perform various bitwise operations on two numbers a and b. The results are printed in binary format to help visualize the manipulation of individual bits.

Common Mistakes

  1. Misunderstanding the binary representation: Familiarize yourself with the binary system and practice converting decimal numbers to binary and vice versa. This will help you understand how bitwise operations work on individual bits.
  2. Confusing bitwise operators with arithmetic ones: Be aware of the differences between bitwise AND, OR, XOR, and their arithmetic counterparts (multiplication, addition, etc.). It's essential to understand when to use each type of operator.
  3. Neglecting the order of operations: Remember that bitwise operators have a higher precedence than arithmetic operators. Use parentheses to ensure correct evaluation and avoid confusion.
  4. Ignoring the sign bit during right shift: When shifting a negative number to the right, the sign bit (most significant bit) is replicated to fill vacated positions. This can lead to unexpected results, so it's important to be aware of this behavior when working with signed integers.
  5. Misusing bitwise operators for arithmetic purposes: While it's possible to perform some arithmetic operations using bitwise operators (e.g., counting set bits), it's generally not recommended, as it can make code more difficult to understand and maintain.

Common Mistakes - Subheadings

  • Misunderstanding the binary representation
  • Converting decimal numbers to binary
  • Understanding powers of 2 in binary
  • Confusing bitwise operators with arithmetic ones
  • Bitwise AND vs logical AND
  • Bitwise OR vs addition
  • Bitwise XOR vs exclusive OR
  • Neglecting the order of operations
  • Using parentheses to clarify operator precedence
  • Ignoring the sign bit during right shift
  • Understanding two's complement representation
  • Handling negative numbers during right shifts
  • Misusing bitwise operators for arithmetic purposes
  • Counting set bits using bitwise AND and XOR
  • Using bitwise operators for multiplication or division

Practice Questions

  1. Calculate the result of 25 & 19 and explain the binary representation.
  2. What is the output of ~7? Explain the binary representation.
  3. Perform the bitwise operations on 45 and 128 (AND, OR, XOR, NOT) and explain the results.
  4. Shift the number 10101010 to the left by 3 places using the bitwise shift operator. What is the output? Explain the binary representation.
  5. Write a Python program that checks if a given number is even or odd using only bitwise operations.
  6. Implement a function that counts the set bits (bits with a value of 1) in an integer using only bitwise operators.
  7. Given two integers, write a function that finds their greatest common divisor (GCD) using the binary GCD algorithm.
  8. Write a Python program to find the number of bits required to represent the decimal number N in binary format.
  9. Implement a function that swaps the least significant bit and the most significant bit of an integer using only bitwise operators.
  10. Write a Python program to determine if a given number is a power of 2 using only bitwise operators.

FAQ

  1. Why are bitwise operators important in programming?

Bitwise operators enable efficient manipulation of individual bits within an integer, which can lead to faster execution times and smaller memory footprints in certain scenarios. They are also essential for understanding low-level programming concepts and solving complex problems.

  1. What is the difference between bitwise AND and logical AND?

Bitwise AND (&) operates on individual bits within integers, while logical AND (and) compares truth values of boolean expressions.

  1. Can I perform bitwise operations on floating-point numbers in Python?

No, bitwise operators are only defined for integers in Python. Attempting to apply them to floating-point numbers will result in a TypeError.

  1. What is the purpose of the bitwise NOT operator (~) in Python?

The bitwise NOT operator flips all the bits in an integer. This can be useful for various purposes like checking if a number is odd or even, toggling bits, and more.

  1. Why do we have to shift the number by 1 when using bitwise AND to find the least significant bit?

To check the least significant bit (LSB) of a number, we can use bitwise AND with a number that has a 1 in the desired position and zeros everywhere else. Shifting this number by 1 ensures that only the LSB is checked. For example: n & 1 checks the LSB of n.

  1. How can I check if a number is a power of two using bitwise operators?

To check if a number is a power of two, we can use the bitwise AND operator with the number and its successor, then compare the result to the original number. For example: n & (n - 1) == 0 checks if n is a power of two. This works because powers of two are the only numbers whose binary representation has a single 1 followed by zeros.

  1. What is the difference between bitwise OR and logical OR?

Bitwise OR (|) operates on individual bits within integers, while logical OR (or) compares truth values of boolean expressions. The bitwise OR operator produces a 1 when at least one of the corresponding bits is 1, whereas the logical OR operator returns True if at least one of the operands is True.

  1. What are some real-world applications of bitwise operators?

Bitwise operators are used extensively in various areas like cryptography, game development, and system programming. They enable efficient manipulation of individual bits within an integer, which can lead to smaller memory footprints and faster execution times in certain scenarios. Examples include data compression, encryption algorithms, and low-level system programming tasks.

  1. How can I use bitwise operators to count the number of set bits (bits with a value of 1) in an integer?

To count the number of set bits (also known as population count or Hamming weight) in an integer, we can perform a series of bitwise AND operations and then count the number of non-zero results. This process can be optimized using a lookup table or a combination of bitwise AND and XOR operations for faster execution times.

  1. What is the difference between left shift (<<) and right shift (>>) operators in Python?

Left shift (<<) moves the bits to the left by a specified number of places, filling vacated positions with zeros. Right shift (>>) moves the bits to the right by a specified number of places, filling vacated positions with either zeros or the sign bit for negative numbers. The number of places to shift is specified as an integer argument.

Example of Python Bitwise Operators | Python | XQA Learn