Created
June 4, 2020 02:01
-
-
Save redwrasse/29291e31c746cba8c4ca931869c0ca2c to your computer and use it in GitHub Desktop.
a redundant bits encoder
This file contains hidden or 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
""" | |
a basic redundant bits encoder-decoder | |
""" | |
import json | |
import random | |
import sys | |
SAMPLE_PAYLOAD = {"foo": 1, "bar": 2} | |
FLIP_PROB = 0.05 | |
def dict_to_bytes(d): | |
""" dict to bytes """ | |
return json.dumps(d).encode() | |
def bytes_to_bits(bytes_obj): | |
""" bytes to a binary string """ | |
return bin(int.from_bytes(bytes_obj, byteorder=sys.byteorder))[2:] | |
def bits_to_bytes(bits): | |
""" a binary string to bytes """ | |
return int(bits, 2).to_bytes((len(bits) + 7) // 8, byteorder=sys.byteorder) | |
def redundant_enc(bits): | |
""" encode a binary string by repeating each bit 3 times """ | |
enc_bits = '' | |
for b in bits: | |
enc_bits += b * 3 | |
return enc_bits | |
def random_noise(bits, p): | |
""" flip each bit with probability p""" | |
modified_bits = '' | |
for b in bits: | |
if random.uniform(0, 1) <= p: | |
modified_bits += str((int(b) + 1) % 2) | |
else: | |
modified_bits += b | |
return modified_bits | |
def redundant_decode(enc_bits): | |
""" decode a binary string by taking the majority vote of each consecutive set of 3 bits""" | |
dec_bits = '' | |
n = len(enc_bits) | |
i = 0 | |
while i < n: | |
enc_part = enc_bits[i:i+3] | |
k = sum([int(b) for b in enc_part]) | |
if k > 1: | |
dec_bits += '1' | |
else: | |
dec_bits += '0' | |
i += 3 | |
return dec_bits | |
bytes_payload = dict_to_bytes(SAMPLE_PAYLOAD) | |
bits_payload = bytes_to_bits(bytes_payload) | |
print(f"bits payload: {bits_payload}") | |
enc_bits = redundant_enc(bits_payload) | |
print(f"encoded bits: {enc_bits}") | |
modified_bits = random_noise(enc_bits, FLIP_PROB) | |
print(f"modified bits: {modified_bits}") | |
dec_bits = redundant_decode(modified_bits) | |
print(f"decoded bits: {dec_bits}") | |
dec_bytes = bits_to_bytes(dec_bits) | |
print(f"decoded bytes: {dec_bytes}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment