-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompileBase5.py
More file actions
120 lines (80 loc) · 2.97 KB
/
CompileBase5.py
File metadata and controls
120 lines (80 loc) · 2.97 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"""File compiles 5 bit machine code to Base 5 and vise versa
Author: Drake Setera
Date: 6/20/2025
Version: 3.1.0
"""
class Compiled5Bit:
"""Class converts 5 bit machine code of inputted file to a new file containing Base 5 code and vise versa
"""
def __init__(self, file_name: str, display_error: bool = True):
self.display_error = display_error
if file_name.endswith('.5b'):
self.Binary_to_Base5(file_name)
elif file_name.endswith('.b5'):
self.Base5_to_Binary(file_name)
else:
if self.display_error:
print('Wrong File Type')
raise TypeError
def Binary_to_Base5(self, file_name: str):
"""Creates a Base 5 file with the Base 5 equivalent of the Binary file provided
Args:
file_name (str): Binary file to convert
"""
try:
file = open(f"Code/Binary/{file_name}")
binary = file.read()
file.close()
except:
if self.display_error:
print("Couldn't find file")
base5 = ''
for i in range(0, len(binary), 5):
base5 += self.convert_binary(binary[i:i+5])
file_name = file_name.removesuffix('5b') + 'b5'
file = open(f"Code/Base5/{file_name}", 'w')
file.write(base5)
file.close()
def convert_binary(self, binary: str) -> str:
"""Converts binary instruction into base 5
Args:
binary (str): 5 bit instruction
Returns:
str: base 5 equivalent
"""
val = int(binary,2)
if val < 10:
return str(val)
else:
return chr(val + 55)
def Base5_to_Binary(self, file_name: str):
"""Creates a Binary file with the Binary equivalent of the Base 5 file provided
Args:
file_name (str): Base 5 file to convert
"""
try:
file = open(f"Code/Base5/{file_name}")
base5 = file.read()
file.close()
except:
if self.display_error:
print("Couldn't find file")
binary = ''
for b in base5:
binary += self.convert_base5(b)
file_name = file_name.removesuffix('b5') + '5b'
file = open(f"Code/Binary/{file_name}", 'w')
file.write(binary)
file.close()
def convert_base5(self, base5: str) -> str:
"""Converts base 5 instruction into binary
Args:
binary (str): Base 5 instruction
Returns:
str: binary equivalent
"""
if base5.isdigit():
base5 = int(base5)
return bin(base5).removeprefix('0b').zfill(5)
else:
return bin(ord(base5) - 55).removeprefix('0b').zfill(5)