generated from mwc/lab_compression
42 lines
942 B
Python
42 lines
942 B
Python
from custom_codecs.register import register_codec
|
|
from easybits import Bits
|
|
import string
|
|
|
|
|
|
chars = string.ascii_uppercase + " "
|
|
char_to_num = {c: i for i, c in enumerate(chars)}
|
|
num_to_char = {i: c for i, c in enumerate(chars)}
|
|
|
|
def encode(text):
|
|
text = text.upper()
|
|
result = Bits()
|
|
|
|
for ch in text:
|
|
if ch in char_to_num:
|
|
num = char_to_num[ch]
|
|
b = Bits(uint=num, length=5)
|
|
result = result.concat(b)
|
|
|
|
|
|
while len(result) % 8 != 0:
|
|
result = result.concat(Bits('0'))
|
|
|
|
return result.bytes
|
|
|
|
def decode(data):
|
|
bits = Bits(data)
|
|
text = ""
|
|
|
|
for i in range(0, len(bits), 5):
|
|
chunk = bits[i:i+5]
|
|
if len(chunk) < 5:
|
|
break
|
|
num = chunk.uint
|
|
if num in num_to_char:
|
|
text += num_to_char[num]
|
|
|
|
return text
|
|
|
|
|
|
register_codec(encode, decode, "ascii5")
|