Skip to content

Instantly share code, notes, and snippets.

@khayyamsaleem
Created September 24, 2020 04:08
Show Gist options
  • Save khayyamsaleem/dd1d0e893b07c285c9780060074cbc70 to your computer and use it in GitHub Desktop.
Save khayyamsaleem/dd1d0e893b07c285c9780060074cbc70 to your computer and use it in GitHub Desktop.
from typing import List
def get_bit(n: int, x: int) -> int:
bit = n&(1<<x)
return 0 if bit == 0 else 1
def set_bit(n: int, x: int, b: int) -> int:
return n&(~(1<<x)) if b == 0 else n|(1<<x)
def encode_chunk(word: str) -> int:
output = 0
for i,char in enumerate(map(ord, word)):
for c,j in enumerate(range(i,32,4)):
output = set_bit(output, j, get_bit(char, c))
return output
def encode(text: str) -> List[int]:
n = 4
chunks = [text[i:i+n] for i in range(0, len(text), n)]
encoded = [encode_chunk(chunk) for chunk in chunks]
return encoded
def get_last_n_bits(num, n):
mask = (1 << n) - 1
return num & mask
def decode_chunk(encoded: int) -> int:
decoded = 0
c = 0
for i in range(8):
for j in range(i, 32, 8):
# print(f"setting {j} bit of decoded to ({c}, {get_bit(encoded, c)})")
decoded = set_bit(decoded, j, get_bit(encoded,c))
c += 1
return decoded
def decode(encoded: List[int]) -> List[int]:
out = ""
for encoded_chunk in encoded:
decoded_chunk = decode_chunk(encoded_chunk)
for i in range(4):
out += chr(get_last_n_bits(decoded_chunk, 8))
decoded_chunk = decoded_chunk >> 8
return out
if __name__ == "__main__":
print(encode("ryan"))
print(encode("tacocat"))
print(encode("never odd or even"))
print(encode("FRED"))
print(decode(encode("FRED")))
print(decode(encode("tacocat")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment