Skip to content

Instantly share code, notes, and snippets.

@Barakat
Created June 27, 2018 19:30
Show Gist options
  • Save Barakat/7abed27bbbfbd3f23ca09372853f4d65 to your computer and use it in GitHub Desktop.
Save Barakat/7abed27bbbfbd3f23ca09372853f4d65 to your computer and use it in GitHub Desktop.
Encode binary data into uppercase-only ASCII
ASCII_A_CODE = ord('A')
def ascii_upper_encode(data):
code = ''
for byte in data:
code += chr((byte >> 4) + ASCII_A_CODE)
code += chr((byte & 0xf) + ASCII_A_CODE)
return code
def ascii_upper_decode(code):
code_size = len(code)
assert code_size % 2 == 0
i = 0
data = b''
while i < code_size:
character0 = code[i]
character1 = code[i + 1]
assert 'A' <= character0 <= 'P'
assert 'A' <= character1 <= 'P'
data += bytes([((ord(character1) - ASCII_A_CODE) & 0xf) | ((ord(character0) - ASCII_A_CODE) << 4)])
i += 2
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment