Created
September 24, 2020 04:07
-
-
Save khayyamsaleem/845e43a1d73ad21ea8f5c7af72f2862c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]: | |
total = "" | |
for encoded_chunk in encoded: | |
out = "" | |
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 | |
total += out | |
return total | |
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