DALGLI0/main.py
2018-06-15 16:50:33 +02:00

86 lines
2.0 KiB
Python

def encode(m):
message = format(int.from_bytes(m.encode("latin-1"), "big"), "b")
generator = "10001000000100001"
gen_deg = len(generator)
message += "0" * (gen_deg - 1)
while len(message) % 8 != 0:
message = "0" + message
swapped = list(message)
for i in range(gen_deg - 1):
if swapped[i] == "0":
swapped[i] = "1"
else:
swapped[i] = "0"
message = "".join(swapped)
while True:
if message[0] == "0":
message = message[1:]
else:
chunk = message[:gen_deg]
if len(chunk) < gen_deg:
while len(chunk) % 8 != 0:
chunk = "0" + chunk
return m + chr(int(chunk[:8], 2)) + chr(int(chunk[8:], 2))
remainder = format(int(chunk, 2) ^ int(generator, 2), "b")
message = remainder + message[gen_deg:]
def decode(n):
message = format(int.from_bytes(n.encode("latin-1"), "big"), "b")
generator = "10001000000100001"
gen_deg = len(generator)
while len(message) % 8 != 0:
message = "0" + message
swapped = list(message)
for i in range(gen_deg - 1):
if swapped[i] == "0":
swapped[i] = "1"
else:
swapped[i] = "0"
message = "".join(swapped)
while True:
if '1' not in message:
return True
if message[0] == "0":
message = message[1:]
else:
chunk = message[:gen_deg]
if len(chunk) < gen_deg:
return False
remainder = format(int(chunk, 2) ^ int(generator, 2), "b")
message = remainder + message[gen_deg:]
if __name__ == "__main__":
choice = ""
while choice != "3":
choice = input("1. Utwórz FCS\n2. Sprawdź FCS\n3. Wyjdź\n")
if choice == "1":
inp = input("Wprowadź wiadomość:\n")
print(encode(inp))
elif choice == "2":
inp = input("Wprowadź wiadomość z ramką:\n")
print(decode(inp))