binaryCalculatorPrototype/bitutilities.py

47 lines
1.7 KiB
Python
Raw Normal View History

from collections import deque
2023-06-17 21:41:51 +03:00
class BasicRegister:
2023-06-25 19:39:37 +03:00
"""The BasicRegister represents a hardware register capable of manipulating multiple bits at a time.
:param deque[bool] memory: The bits stored inside the register.
2023-06-25 19:39:37 +03:00
"""
2023-06-17 21:41:51 +03:00
def __init__(self, memory: list[bool]):
2023-06-25 19:39:37 +03:00
"""Constructor method"""
self.memory: deque[bool] = deque(memory)
2023-06-17 21:41:51 +03:00
def __str__(self) -> str:
2023-06-18 15:02:29 +03:00
return f"Memory: {[int(value) for value in self.memory]}"
2023-06-17 21:41:51 +03:00
def reverse(self):
self.memory = deque([not value for value in self.memory])
2023-06-17 21:41:51 +03:00
def left_shift(self, digit_to_fill: bool = False, steps_shifted: int = 1) -> deque[bool]:
2023-06-18 14:51:13 +03:00
self.memory.extend([digit_to_fill] * steps_shifted)
shifted_radices: deque[bool] = deque([self.memory.popleft() for _i in range(steps_shifted)])
2023-06-17 21:41:51 +03:00
return shifted_radices
def right_shift(self, digit_to_fill: bool = False, steps_shifted: int = 1) -> deque[bool]:
self.memory.extendleft([digit_to_fill] * steps_shifted)
shifted_radices: deque[bool] = deque([self.memory.pop() for _i in range(steps_shifted)])
2023-06-17 21:41:51 +03:00
return shifted_radices
def get_memory(variable_name: str) -> list[bool]:
"""
Reads user input to be used as a memory array.
:param str variable_name: The name to be displayed in the input line.
:return: A list of boolean values read from user.
:rtype: list[bool]
"""
while True:
input_chars: list[str] = list(input(f"Enter {variable_name}: "))
if all(character in ["0", "1"] for character in input_chars):
return [True if character == "1" else False for character in input_chars]
else:
print(f"[ERROR] The {variable_name} may contain only 1-s and 0-s!")