Search⌘ K
AI Features

Bitwise Operators

Explore the use of bitwise operators in Python to perform low-level data manipulation on integers. This lesson explains bitwise AND, OR, XOR, NOT, and bit shifts, demonstrating their applications in tasks such as flag management, encryption, and checking if numbers are even or odd.

In computing and digital communication, the data is actually made up of 0s and 1s known as bits. Bits are the smallest unit of data.

Bitwise operators allow us to perform bit-related operations on values.

Bitwise operations find use in several real world applications. They are used for various image processing tasks. Many encryption algorithms utilize bitwise operations for scrambling data. Bit flags are a common technique to represent multiple states or options using a single byte instead of multiple variables; bitwise operations are used to set, clear, or check individual flags.

Bit manipulation

Bit manipulation involves directly working with the binary representation of numbers. It allows for efficient and low-level data processing. Bitwise operators in Python only work on integer values. Below are the bitwise operators with a brief explanation:

  • Bitwise AND (&):

    • The bitwise AND operator & compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

    • Example: 5 & 3 (binary 0101 & 0011) results in 0001 (decimal 1).

  • Bitwise OR (|):

...