generated from mwc/lab_compression
Wrote codes for ascii5.py based on ascii7.py.
This commit is contained in:
41
text_codecs/ascii5.py
Normal file
41
text_codecs/ascii5.py
Normal file
@@ -0,0 +1,41 @@
|
||||
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")
|
||||
Reference in New Issue
Block a user