Fix message encoding, add decoding
This commit is contained in:
parent
538b8393d9
commit
0839e48c9f
54
main.py
54
main.py
@ -1,10 +1,10 @@
|
|||||||
def encode(M):
|
def encode(m):
|
||||||
message = format(int.from_bytes(M.encode(), "big"), "b")
|
message = format(int.from_bytes(m.encode("latin-1"), "big"), "b")
|
||||||
generator = "10001000000100001"
|
generator = "10001000000100001"
|
||||||
gen_deg = len(generator)
|
gen_deg = len(generator)
|
||||||
|
|
||||||
message += "0" * (gen_deg - 1)
|
message += "0" * (gen_deg - 1)
|
||||||
if len(message) % 2 != 0:
|
while len(message) % 8 != 0:
|
||||||
message = "0" + message
|
message = "0" + message
|
||||||
|
|
||||||
swapped = list(message)
|
swapped = list(message)
|
||||||
@ -24,26 +24,50 @@ def encode(M):
|
|||||||
chunk = message[:gen_deg]
|
chunk = message[:gen_deg]
|
||||||
|
|
||||||
if len(chunk) < gen_deg:
|
if len(chunk) < gen_deg:
|
||||||
chunk = "00" + chunk
|
|
||||||
return chr(int(chunk[:8], 2)) + chr(int(chunk[8:], 2))
|
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")
|
remainder = format(int(chunk, 2) ^ int(generator, 2), "b")
|
||||||
message = remainder + message[gen_deg:]
|
message = remainder + message[gen_deg:]
|
||||||
|
|
||||||
|
|
||||||
def decode(N):
|
def decode(n):
|
||||||
message = format(int.from_bytes(N.encode(), "big"), "b")
|
message = format(int.from_bytes(n.encode("latin-1"), "big"), "b")
|
||||||
|
generator = "10001000000100001"
|
||||||
|
gen_deg = len(generator)
|
||||||
|
|
||||||
while len(message) % 8 != 0:
|
while len(message) % 8 != 0:
|
||||||
message = "0" + message
|
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__":
|
if __name__ == "__main__":
|
||||||
M = input()
|
print()
|
||||||
N = encode(M)
|
|
||||||
# print(N)
|
|
||||||
decode(M+N)
|
|
||||||
# 0011110110111000
|
|
||||||
# 11000010111100101111001001111011100001010111000
|
|
||||||
# 0011110110111000
|
|
||||||
|
Loading…
Reference in New Issue
Block a user