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 (&):

    • Compares each bit of two numbers. If both bits are 1, the resulting bit is 1; otherwise, it is 0.

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

  • Bitwise OR (|):

    • Compares each bit of two numbers. If at least one of the bits is 1, the resulting bit is 1; otherwise, it is 0.

    • Example: 5 | 3 (binary 0101 | 0011) results in 0111 (decimal 7).

  • Bitwise XOR (^):

    • Compares each bit of two numbers. If the bits are different, the resulting bit is 1; otherwise, it is 0.

    • Example: 5 ^ 3 (binary 0101 ^ 0011) results in 0110 (decimal 6).

  • Bitwise NOT (~):

    • Inverts all the bits of a number, changing 1s to 0s and 0s to 1s.

    • Example: ~5 (binary 0101) results in 1010 (decimal -6, due to two's complement representation).

  • Shift Bits Left (<<):

    • Shifts the bits of a number to the left by a specified number of positions. Each shift to the left doubles the number.

    • Example: 5 << 1 (binary 0101 shifted left by 1) results in 1010 (decimal 10).

    • The bitshift operations (<< and >>) simply move the bits to either the right or the left. When a binary number is shifted, a 0 also enters at the opposite end to keep the number the same size.

  • Shift Bits Right (>>):

    • Shifts the bits of a number to the right by a specified number of positions. Each shift to the right halves the number.

    • Example: 5 >> 1 (binary 0101 shifted right by 1) results in 0010 (decimal 2).

    • The bitshift operations (<< and >>) simply move the bits to either the right or the left. When a binary number is shifted, a 0 also enters at the opposite end to keep the number the same size.

In Python, leading zeroes are truncated. For example, the number 0011 will be the same as 11. Similarly, the number 0001011 will be the same as 1011.

Get hands-on with 1400+ tech skills courses.