Table of contents
1.
Introduction
2.
Understanding the Basics of Hamming Code
3.
How Does Hamming Code Work?
3.1.
The Mathematics Behind It
4.
Creating & Implementing Hamming Code in Python
4.1.
Step 1: Calculating Parity Bits
4.2.
Step 2: Positioning the Parity Bits
4.3.
Step 3: Calculating Parity Bits' Values
4.4.
Step 4: Error Detection & Correction
5.
Integrating Functions into a Complete Program
5.1.
Python
6.
Practical Applications of Hamming Code
6.1.
Computer Memory (RAM) 
6.2.
Wireless Communication 
6.3.
Data Storage Devices
7.
Frequently Asked Questions
7.1.
Why is Hamming Code important in computer networks?
7.2.
Can Hamming Code correct multiple-bit errors?
7.3.
Is Hamming Code still relevant with modern error correction methods?
8.
Conclusion
Last Updated: Aug 13, 2025
Easy

Hamming Code in Python

Introduction

Have you ever wondered how data transmitted over networks remains error-free? The secret lies in clever coding techniques, one of which is the Hamming Code. This article delves into the world of Hamming Code, a method for error detection & correction. Specifically, we'll explore its implementation in Python. 

Hamming Code in Python

By the end of this read, you'll understand the basics of Hamming Code, how to implement it in Python, & appreciate its significance in maintaining data integrity. Let's embark on this coding journey together!

Understanding the Basics of Hamming Code

Hamming Code is a set of error-correction codes that can detect & correct single-bit errors in data transmission or storage. Named after its inventor, Richard Hamming, this code is a staple in computer networks & digital communication systems.

How Does Hamming Code Work?

Hamming Code works by adding extra bits, known as parity bits, to the original data bits. These parity bits are calculated based on specific positions of the data bits, ensuring any single-bit error can be identified & corrected. The beauty of this technique is its simplicity & efficiency in detecting & correcting errors.

The Mathematics Behind It

To create a Hamming Code, we first determine the number of parity bits required. This is calculated using the formula 

2p≥m+p+1, where 

p is the number of parity bits & 

is the number of data bits. Once we know the number of parity bits, we can place them at positions that are powers of 2 (i.e., 1, 2, 4, 8, etc.).

Creating & Implementing Hamming Code in Python

Step 1: Calculating Parity Bits

First, we need a function to calculate the number of parity bits required. Let's write a simple Python function for this:

def calculate_parity_bits(m):
    p = 0
    while (2 ** p) < m + p + 1:
        p += 1
    return p
You can also try this code with Online Python Compiler
Run Code


This function takes the number of data bits m & calculates the minimum number of parity bits p needed.

Step 2: Positioning the Parity Bits

Next, we insert the parity bits at the correct positions. For this, we create another function:

def position_parity_bits(data, p):
    j = 0
    k = 1
    m = len(data)
    result = ''
    for i in range(1, m + p + 1):
        if i == 2 ** j:
            result += '0'
            j += 1
        else:
            result += data[-k]
            k += 1
    return result[::-1]
You can also try this code with Online Python Compiler
Run Code

In this function, we iterate through each position & add a '0' (placeholder for parity bits) at positions that are powers of 2. The rest of the positions are filled with the original data bits.

Step 3: Calculating Parity Bits' Values

Now, we need to calculate the values of these parity bits. Here's how we do it:

def calculate_parity_values(code, p):
    n = len(code)
    for i in range(p):
        val = 0
        for j in range(1, n + 1):
            if j & (2 ** i) == (2 ** i):
                val = val ^ int(code[-j])
        code = code[:n-(2**i)] + str(val) + code[n-(2**i)+1:]
    return code
You can also try this code with Online Python Compiler
Run Code


In this function, we use bitwise operations to determine which bits to include for each parity calculation & then calculate their values using XOR.

Step 4: Error Detection & Correction

Finally, we create a function to detect & correct errors in the received Hamming Code:

def detect_correct_error(code, p):
    n = len(code)
    error_pos = 0
    for i in range(p):
        val = 0
        for j in range(1, n + 1):
            if j & (2 ** i) == (2 ** i):
                val = val ^ int(code[-j])
        error_pos += val * (2 ** i)
    if error_pos:
        print(f"Error found at position: {error_pos}")
        corrected_code = code[:n - error_pos] + str(1 - int(code[n - error_pos])) + code[n - error_pos + 1:]
        return corrected_code
    else:
        print("No error detected.")
        return code
You can also try this code with Online Python Compiler
Run Code


This function calculates the error position & corrects the code if an error is found.

Integrating Functions into a Complete Program

The Complete Python Program for Hamming Code

Now, we'll integrate the functions we've created into a complete program. Here's how it looks:

  • Python

Python

def main():

   original_data = input("Enter the data bits: ")

   m = len(original_data)

   p = calculate_parity_bits(m)


   positioned_data = position_parity_bits(original_data, p)

   hamming_code = calculate_parity_values(positioned_data, p)

   print(f"Hamming Code: {hamming_code}")

   received_code = input("Enter the received Hamming Code: ")

   corrected_code = detect_correct_error(received_code, p)




   print(f"Corrected Hamming Code: {corrected_code}")


if __name__ == "__main__":

   main()

Complete code

def calculate_parity_bits(m):

   p = 0

   while (2 ** p) < m + p + 1:

       p += 1

   return p


def position_parity_bits(data, p):

   j = 0

   k = 1

   m = len(data)

   result = ''


   for i in range(1, m + p + 1):

       if i == 2 ** j:

           result += '0'

           j += 1

       else:

           result += data[-k]

           k += 1




   return result[::-1]



def calculate_parity_values(code, p):

   n = len(code)

   for i in range(p):

       val = 0

       for j in range(1, n + 1):

           if j & (2 ** i) == (2 ** i):

               val = val ^ int(code[-j])

       code = code[:n-(2**i)] + str(val) + code[n-(2**i)+1:]

   return code


def detect_correct_error(code, p):

   n = len(code)

   error_pos = 0

   for i in range(p):

       val = 0

       for j in range(1, n + 1):

           if j & (2 ** i) == (2 ** i):

               val = val ^ int(code[-j])

       error_pos += val * (2 ** i)


   if error_pos:

       print(f"Error found at position: {error_pos}")

       corrected_code = code[:n - error_pos] + str(1 - int(code[n - error_pos])) + code[n - error_pos + 1:]

       return corrected_code

   else:

       print("No error detected.")

       return code


def main():

   original_data = input("Enter the data bits: ")

   m = len(original_data)

   p = calculate_parity_bits(m)



   positioned_data = position_parity_bits(original_data, p)

   hamming_code = calculate_parity_values(positioned_data, p)


   print(f"Hamming Code: {hamming_code}")



   received_code = input("Enter the received Hamming Code: ")

   corrected_code = detect_correct_error(received_code, p)


   print(f"Corrected Hamming Code: {corrected_code}")


if __name__ == "__main__":

   main()
You can also try this code with Online Python Compiler
Run Code


Output

Output

To run this program, simply copy the code into a Python environment. Input your data bits, and the program will generate the corresponding Hamming Code. Then, you can input a received Hamming Code (with potential errors) to see the error detection and correction in action.

Practical Applications of Hamming Code

Hamming Code isn't just a theoretical concept. It's widely used in various real-world applications:

Computer Memory (RAM) 

Hamming Code is used to detect & correct errors in RAM. It ensures data integrity, which is crucial for system stability.

Wireless Communication 

In wireless networks, Hamming Code helps in maintaining the accuracy of data transmitted over airwaves, where interference is common.

Data Storage Devices

Hamming Code is also implemented in hard drives and solid-state drives to prevent data corruption.

Frequently Asked Questions

Why is Hamming Code important in computer networks?

Hamming Code ensures data integrity in transmissions, which is essential for reliable communication in networks.

Can Hamming Code correct multiple-bit errors?

No, Hamming Code is designed to detect & correct only single-bit errors.

Is Hamming Code still relevant with modern error correction methods?

Yes, due to its simplicity & efficiency, it's still used in many applications, particularly where resource efficiency is key.

Conclusion

Hamming Code is a fascinating & vital part of data transmission and storage. Understanding & implementing it in Python not only boosts your coding skills but also gives you a deeper appreciation of the mechanisms that keep our digital world running smoothly. Keep exploring & happy coding!

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass