-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManchesterEncoding.py
More file actions
101 lines (68 loc) · 2.24 KB
/
Copy pathManchesterEncoding.py
File metadata and controls
101 lines (68 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from pathlib import Path
INPUT_FILE = "input.txt"
OUTPUT_FILE = "received_file.txt"
# Manchester rule:
# 0 -> 10
# 1 -> 01
def file_to_bits(filename):
text = Path(filename).read_text(encoding="utf-8").rstrip("\r\n")
data = text.encode("utf-8")
bits = ""
for byte in data:
bits += format(byte, "08b")
return bits, len(data)
def bits_to_manchester(bits):
encoded = ""
for bit in bits:
if bit == "0":
encoded += "10"
elif bit == "1":
encoded += "01"
return encoded
def manchester_to_bits(encoded):
bits = ""
errors = 0
if len(encoded) % 2 != 0:
errors += 1
encoded = encoded[:-1]
for i in range(0, len(encoded), 2):
pair = encoded[i:i+2]
if pair == "10":
bits += "0"
elif pair == "01":
bits += "1"
else:
bits += "0"
errors += 1
return bits, errors
def bits_to_file(bits, output_filename, original_size):
data = bytearray()
for i in range(0, len(bits), 8):
byte = bits[i:i+8]
if len(byte) == 8:
data.append(int(byte, 2))
data = data[:original_size]
Path(output_filename).write_bytes(data)
def compare_files(file1, file2):
original = Path(file1).read_text(encoding="utf-8").rstrip("\r\n").encode("utf-8")
received = Path(file2).read_bytes()
return original == received
def main():
bits, original_size = file_to_bits(INPUT_FILE)
manchester = bits_to_manchester(bits)
decoded_bits, decode_errors = manchester_to_bits(manchester)
bits_to_file(decoded_bits, OUTPUT_FILE, original_size)
success = compare_files(INPUT_FILE, OUTPUT_FILE)
Path("binary.txt").write_text(bits, encoding="utf-8")
Path("manchester.txt").write_text(manchester, encoding="utf-8")
Path("decoded_bits.txt").write_text(decoded_bits, encoding="utf-8")
print("Manchester Encoding Project")
print("---------------------------")
print("Input file:", INPUT_FILE)
print("Output file:", OUTPUT_FILE)
print("Original bits:", len(bits))
print("Manchester bits:", len(manchester))
print("Decode errors:", decode_errors)
print("Transmission success:", success)
if __name__ == "__main__":
main()