Bit Manipulation in Python: A beginner’s guide

Shreya Shrivastava
4 min readFeb 18, 2024

--

Photo by Michael Pointner on Unsplash

Bit manipulation is important because it allows programmers to efficiently work with individual bits in data. This leads to optimized algorithms, compact data representation, and efficient use of resources. It’s essential in systems programming, cryptography, networking, game development, and embedded systems. Mastering bit manipulation enhances a programmer’s ability to write efficient code and solve complex problems across various domains. However, it can be a bit difficult to grasp at the beginning. Here is a simplified explanation of this crucial concept.

Bit manipulation involves performing operations at the binary level on individual bits within binary numbers. In Python, you can perform bitwise operations on integers, which treat the numbers as sequences of binary digits (bits).

Here are some common bitwise operators in Python:

AND (&): This operator compares each bit of two numbers. If both bits are 1, the result is 1; otherwise, it’s 0.

OR (|): This operator compares each bit of two numbers. If at least one of the bits is 1, the result is 1; otherwise, it’s 0.

XOR (^): This operator compares each bit of two numbers. If the bits are different, the result is 1; if they are the same, the result is 0.

NOT (~): This operator flips all the bits in a number. All 0s become 1s, and all 1s become 0s. Note that this operation can also depend on the size of the integer (due to two’s complement representation).

Shift Left (<<): This operator shifts the bits of a number to the left by a specified number of positions, effectively multiplying the number by 2 raised to the power of the shift amount.

Shift Right (>>): This operator shifts the bits of a number to the right by a specified number of positions, effectively dividing the number by 2 raised to the power of the shift amount (integer division).

Here’s a simple example of performing some bitwise operations in Python:

# Define two numbers in binary
a = 0b1010 # 10 in decimal
b = 0b1100 # 12 in decimal

# Bitwise AND
result_and = a & b # 0b1000 (8 in decimal)
print("Bitwise AND:", bin(result_and))

# Bitwise OR
result_or = a | b # 0b1110 (14 in decimal)
print("Bitwise OR:", bin(result_or))

# Bitwise XOR
result_xor = a ^ b # 0b0110 (6 in decimal)
print("Bitwise XOR:", bin(result_xor))

# Bitwise NOT
result_not_a = ~a # -11 in decimal (depends on size of integer)
print("Bitwise NOT of a:", bin(result_not_a))

# Left shift
result_left_shift = a << 2 # 0b101000 (40 in decimal)
print("Left Shift of a:", bin(result_left_shift))

# Right shift
result_right_shift = b >> 1 # 0b110 (6 in decimal)
print("Right Shift of b:", bin(result_right_shift))

But wait a minute.

What exactly are binary numbers?

Imagine you’re playing with blocks. You have two types of blocks: a red block and a blue block. These blocks represent the two digits in binary: 0 and 1.

Now, let’s imagine a row of slots. Each slot can either be empty or filled with a block. If it’s empty, we represent it as a 0, and if it’s filled with a block, we represent it as a 1.

So, a binary number is like a sequence of these slots, where each slot can either be empty (0) or filled (1).

For example:

0 in binary is represented as “no blocks”, meaning all slots are empty.
1 in binary is represented as “one block” in the first slot.
10 in binary is represented as “one block” in the second slot, and the first slot is empty.
Here’s how we count in binary:

0, 1, 10, 11, 100, 101, 110, 111, 1000, and so on.
It’s like counting with your blocks: if a slot is empty, you move to the next one, and if it’s filled, you add one more block and continue.

Binary is the language of computers because computers work with switches that can either be “on” (1) or “off” (0), much like our blocks being either present or absent. So, when we write programs or store data on computers, we often use binary numbers to represent information.

How to convert Binary to Decimal?

Converting binary numbers to decimal might sound tricky, but it’s actually quite simple once you understand the process.

Here’s a step-by-step guide in an easy way:

  1. Understand the Binary System: In the binary system, each digit can be either 0 or 1. Each digit’s position represents a power of 2, starting from the rightmost position, which represents 2⁰ (1), then 2¹ (2), 2² (4), and so on, doubling for each position to the left.
  2. Write Down the Binary Number: Let’s say you have a binary number, such as 1011.
  3. Assign Powers of 2 to Each Position: Starting from the right, assign powers of 2 to each position. For 1011:

1 (rightmost position) corresponds to ²⁰ = 1
1 (second position from the right) corresponds to ²¹ = 2
0 (third position from the right) corresponds to ²² = 4
1 (leftmost position) corresponds to ²³ = 8
Multiply Each Digit by Its Corresponding Power of 2: Multiply each digit of the binary number by its corresponding power of 2.

1 * ²³ = 8
0 * ²² = 0
1 * ²¹ = 2
1 * ²⁰ = 1

4. Add Up the Results: Add up all the results from step 4:

8 + 0 + 2 + 1 = 11

5. That’s Your Decimal Number: So, the binary number 1011 is equivalent to the decimal number 11

Conclusion:

That was the complete 101 on binary numbers and how to manipulate them in python. Hope this made your day more magical! 🔮🪄

Photo by Divyansh Dhakaita on Unsplash

Here’s a cute cat to make your day better.

--

--

Shreya Shrivastava

Hi there! I’m Shreya, a college student of bachelors in AI and machine learning. I’ve been dabbling in python and coding for the past 6 years.