Skip to content

Instantly share code, notes, and snippets.

@dogtopus
Last active February 12, 2024 23:45
Show Gist options
  • Save dogtopus/0f1db480b32015fab7f1d3d8ac9a7050 to your computer and use it in GitHub Desktop.
Save dogtopus/0f1db480b32015fab7f1d3d8ac9a7050 to your computer and use it in GitHub Desktop.
I hate eye strains
import itertools
def encode(s: str, encoding: str = 'utf-8', ntet: int = 8, flip: int = 0) -> str:
if ntet < flip:
raise ValueError('ntet must be less than flip.')
if ntet == 8 and flip == 0:
header = ''
elif ntet != 8 and flip == 0:
header = f'{ntet}_'
else:
header = f'{ntet}~{flip}_'
result = [header]
b = s.encode(encoding)
ntet_mask = (1 << ntet) - 1
flip_mask = 1 << (flip - 1) if flip > 0 else 0
ntet_fmt = f'{{num:0{ntet}b}}'
for i, octet in enumerate(b):
num_masked = octet & ntet_mask
if num_masked != octet:
raise ValueError(f'Encoding failed at position {i}: Cannot represent character as a {ntet}-tet')
encoded = ntet_fmt.format(num=num_masked ^ flip_mask)
result.append(encoded)
return ''.join(result)
def decode(s: str, encoding: str = 'utf-8') -> str:
if '_' in s:
header, s = s.split('_')
if '~' in header:
ntet, flip = map(int, header.split('~'))
else:
ntet = int(header)
flip = 0
else:
ntet = 8
flip = 0
result = bytearray()
for bits in itertools.batched(s, ntet):
value = int(''.join(bits), 2)
if flip > 0:
value ^= 1 << (flip - 1)
result.append(value)
return result.decode(encoding)
if __name__ == '__main__':
print(decode('7~4_1011100110000011011010101000110111011001001110001010100011110101111101110011011110110101000110100111111000101000110010111000011101100110011011000011101111110000011111000100110'))
print(encode('I love cookies!', flip=1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment