Created
February 27, 2024 17:08
-
-
Save louis030195/ad6f722e054fc957599af1cb7fba01d8 to your computer and use it in GitHub Desktop.
Self correcting error codes for redundancy against space radiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def generateParityBits(data): | |
""" | |
Generates parity bits for the given 4-bit data. | |
""" | |
p1 = data[0] ^ data[1] ^ data[3] | |
p2 = data[0] ^ data[2] ^ data[3] | |
p3 = data[1] ^ data[2] ^ data[3] | |
return p1, p2, p3 | |
def encodeHamming(data): | |
""" | |
Encodes the 4-bit data using Hamming(7,4) code. | |
""" | |
p1, p2, p3 = generateParityBits(data) | |
# Encoded data: p1, p2, d1, p3, d2, d3, d4 | |
return [p1, p2, data[0], p3, data[1], data[2], data[3]] | |
def decodeHamming(encoded): | |
""" | |
Decodes the 7-bit encoded data and corrects a single-bit error. | |
""" | |
p1, p2, p3 = generateParityBits([encoded[2], encoded[4], encoded[5], encoded[6]]) | |
# Error checking | |
error_pos = p1 * 1 + p2 * 2 + p3 * 4 | |
if error_pos: | |
print(f"Error detected at position: {error_pos}") | |
encoded[error_pos-1] = 1 - encoded[error_pos-1] # Correct the error | |
# Extract the original data | |
return [encoded[2], encoded[4], encoded[5], encoded[6]] | |
# Example usage | |
data = [1, 0, 1, 1] # Original data | |
print("Original data:", data) | |
encoded = encodeHamming(data) | |
print("Encoded data:", encoded) | |
# Introducing a single bit error for demonstration | |
encoded[2] = 0 if encoded[2] == 1 else 1 # Flip the third bit | |
print("Encoded data with error:", encoded) | |
decoded = decodeHamming(encoded) | |
print("Decoded data:", decoded) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AutoHamming
AutoHamming is a Python library that ensures the integrity of your variables by automatically applying Hamming code protection. With AutoHamming, every variable is seamlessly encoded with Hamming code upon assignment and decoded upon access, providing error detection and correction without any manual intervention.
Features
Installation
Quick Start
Using AutoHamming
Import and use the provided data types from AutoHamming to define your variables. These types will automatically apply Hamming code protection.
How It Works
AutoHamming overrides the getter and setter methods of the Python data type classes. When you assign a value to a variable of these custom types, AutoHamming encodes the value using Hamming code. When you access the variable, AutoHamming decodes the value, correcting any errors that can be fixed.
Contributing
Your contributions are welcome! Please feel free to submit pull requests, report bugs, or suggest features.
License
This project is licensed under the MIT License - see the LICENSE file for details.