binaryCalculatorPrototype/bitutilities.py

318 lines
10 KiB
Python
Raw Normal View History

from collections import deque
2023-06-26 21:58:24 +03:00
from typing_extensions import Self
class BasicRegister:
2023-06-26 21:58:24 +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.
"""
def __init__(self, memory: list[bool]):
self.memory: deque[bool] = deque(memory)
def __repr__(self) -> str:
return f"Memory: {[int(value) for value in self.memory]}"
def __str__(self) -> str:
return f"Memory: {[int(value) for value in self.memory]}"
def __len__(self) -> int:
return len(self.memory)
2023-06-26 21:58:24 +03:00
def adjusted_by_size(self, resulting_size: int) -> Self:
"""
Adjusts a register to a given size.
:param int resulting_size: The size of the resulting register.
:return: A register of a specified size.
:rtype: BasicRegister
"""
current_memory_size: int = len(self.memory)
return BasicRegister(
2023-06-26 22:33:41 +03:00
[False] * max(resulting_size - current_memory_size, 0) + list(self.memory)[-resulting_size:]
2023-06-26 21:58:24 +03:00
)
def reverse(self):
2023-06-27 17:49:33 +03:00
"""
Performs a logical negation on the register.
"""
self.memory = deque([not value for value in self.memory])
2023-06-27 17:49:33 +03:00
def left_shift(self, shift_in_value: bool = False, bits_shifted: int = 1) -> deque[bool]:
"""
Shifts the register to the left by a specified number of steps
:param bool shift_in_value: The value that shifts inside the freed space.
:param int bits_shifted: The number of bits by which the register is shifted.
:return: The bits shifted outside the register.
:rtype: deque[bool]
"""
self.memory.extend([shift_in_value] * bits_shifted)
shifted_bits: deque[bool] = deque([self.memory.popleft() for _i in range(bits_shifted)])
return shifted_bits
def right_shift(self, shift_in_value: bool = False, bits_shifted: int = 1) -> deque[bool]:
"""
Shifts the register to the right by a specified number of steps
:param bool shift_in_value: The value that shifts inside the freed space.
:param int bits_shifted: The number of bits by which the register is shifted.
2023-06-27 17:49:33 +03:00
:return: The bits shifted outside the register.
:rtype: deque[bool]
"""
self.memory.extendleft([shift_in_value] * bits_shifted)
shifted_bits: deque[bool] = deque([self.memory.pop() for _i in range(bits_shifted)])
return shifted_bits
class Counter:
"""
The Counter represents a hardware register specifically designed for countdowns.
:param int value: Initial numeric value this Counter holds.
"""
def __init__(self, value: int):
self.memory: deque[bool] = deque([i == "1" for i in bin(value)[2:]])
def __repr__(self) -> str:
return f"Memory: {[int(value) for value in self.memory]}"
def __str__(self) -> str:
return f"Memory: {[int(value) for value in self.memory]}"
def __len__(self) -> int:
return len(self.memory)
def decrement(self):
self.memory = binary_subtraction(self, BasicRegister([False] * (len(self.memory) - 1) + [True])).memory
def non_zero(self) -> bool:
return any(self.memory)
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!")
def binary_sum_with_carry(first_term: BasicRegister, second_term: BasicRegister) -> tuple[BasicRegister, int]:
2023-06-27 17:49:33 +03:00
"""
Sums two registers' values and keeps the carry-out.
:param BasicRegister first_term: First register.
:param BasicRegister second_term: Second register.
:return: Register containing the sum and the carry-out bit.
:rtype: tuple[BasicRegister, int]
"""
result_term = BasicRegister([False] * len(first_term))
carry = False
for i in range(len(first_term) - 1, -1, -1):
current_bit_sum = first_term.memory[i] + second_term.memory[i] + carry
carry = bool(current_bit_sum & 2)
result_term.memory[i] = bool(current_bit_sum & 1)
return result_term, carry
def binary_sum(first_term: BasicRegister, second_term: BasicRegister) -> BasicRegister:
"""
2023-06-27 17:49:33 +03:00
Sums two terms containing binary numbers.
2023-06-27 17:49:33 +03:00
:param BasicRegister first_term: First register to add.
:param BasicRegister second_term: Second register to add.
2023-06-27 17:49:33 +03:00
:return: Register containing the sum.
:rtype: BasicRegister
"""
return binary_sum_with_carry(first_term, second_term)[0]
2023-06-27 17:49:33 +03:00
def binary_subtraction(minuend: BasicRegister, subtrahend: BasicRegister) -> BasicRegister:
"""
Subtracts the second term from the first in binary using ones' complement.
:param BasicRegister minuend: Register to subtract from.
:param BasicRegister subtrahend: Register to subtract by.
2023-06-27 17:49:33 +03:00
:return: Register containing the difference.
:rtype: BasicRegister
"""
subtrahend.reverse()
difference: BasicRegister
2023-06-27 15:53:20 +03:00
final_carry: bool
2023-06-27 17:49:33 +03:00
difference, final_carry = binary_sum_with_carry(minuend, subtrahend)
2023-06-27 15:53:20 +03:00
if final_carry:
2023-06-27 17:49:33 +03:00
return binary_sum(difference, BasicRegister([False] * (len(difference) - 1) + [True]))
2023-06-27 15:53:20 +03:00
else:
2023-06-27 17:49:33 +03:00
difference.reverse()
return difference
# def align_registers(first_register: BasicRegister, second_register: BasicRegister) \
# -> tuple[BasicRegister, BasicRegister]:
# """
# Aligns two registers by the length of the bigger one.
#
# :param BasicRegister first_register:
# :param BasicRegister second_register:
#
# :return:
# :rtype: tuple[BasicRegister, BasicRegister]
# """
# first_size = len(first_register)
# second_size = len(second_register)
#
# required_size = max(first_size, second_size)
#
# if first_size != second_size:
# return first_register.adjusted_by_size(required_size), second_register.adjusted_by_size(required_size)
# else:
# return first_register, second_register
2023-06-27 17:53:18 +03:00
def align_registers(*registers: BasicRegister) -> tuple[BasicRegister, ...]:
"""
Aligns registers by the length of the bigger one.
2023-06-27 17:53:18 +03:00
:param BasicRegister registers: Registers to align.
:return: Aligned registers.
:rtype: tuple[BasicRegister, ...]
"""
2023-06-27 17:53:18 +03:00
required_size: int = max(map(len, registers))
return tuple(reg.adjusted_by_size(required_size) for reg in registers)
def binary_multiplication_method_1(first_term: BasicRegister, second_term: BasicRegister) -> BasicRegister:
"""
Multiplies two terms containing binary numbers using first method.
:param BasicRegister first_term: First register to multiply.
:param BasicRegister second_term: Second register to multiply.
:return: Register containing the product.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
rg1 = BasicRegister([False] * n)
rg2 = BasicRegister(first_term.memory)
rg3 = BasicRegister(second_term.memory)
ct = Counter(n)
while ct.non_zero():
if rg2.memory[n-1]:
rg1 = binary_sum(rg1, rg3)
rg2.right_shift(rg1.memory[n-1])
rg1.right_shift()
ct.decrement()
return BasicRegister(list(rg1.memory) + list(rg2.memory))
def binary_multiplication_method_2(first_term: BasicRegister, second_term: BasicRegister) -> BasicRegister:
"""
Multiplies two terms containing binary numbers using second method.
:param BasicRegister first_term: First register to multiply.
:param BasicRegister second_term: Second register to multiply.
:return: Register containing the product.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
rg1 = BasicRegister([False] * (2*n))
rg2 = BasicRegister(first_term.memory)
rg3 = BasicRegister([False] * n + list(second_term.memory))
while any(rg2.memory):
if rg2.memory[n-1]:
rg1 = binary_sum(rg1, rg3)
rg2.right_shift()
rg3.left_shift()
return rg1
def binary_multiplication_method_3(first_term: BasicRegister, second_term: BasicRegister) -> BasicRegister:
"""
Multiplies two terms containing binary numbers using third method.
:param BasicRegister first_term: First register to multiply.
:param BasicRegister second_term: Second register to multiply.
:return: Register containing the product.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
rg1 = BasicRegister([False] * n)
rg2 = BasicRegister(list(first_term.memory) + [False])
rg3 = BasicRegister([False] * (n+1) + list(second_term.memory))
ct = Counter(n)
while ct.non_zero():
if rg2.memory[0]:
result: list[bool] = list(binary_sum(BasicRegister(rg2.memory + rg1.memory), rg3).memory)
rg2 = BasicRegister(result[:n+1])
rg1 = BasicRegister(result[n+1:])
rg2.left_shift(rg1.memory[0])
rg1.left_shift()
ct.decrement()
return BasicRegister((list(rg2.memory) + list(rg1.memory))[:-1])
def binary_multiplication_method_4(first_term: BasicRegister, second_term: BasicRegister) -> BasicRegister:
"""
Multiplies two terms containing binary numbers using fourth method.
:param BasicRegister first_term: First register to multiply.
:param BasicRegister second_term: Second register to multiply.
:return: Register containing the product.
:rtype: BasicRegister
"""
first_term, second_term = align_registers(first_term, second_term)
n: int = len(first_term)
rg1 = BasicRegister([False] * (2*n+1))
rg2 = BasicRegister(first_term.memory)
rg3 = BasicRegister([False] + list(second_term.memory) + [False] * n)
while any(rg2.memory):
if rg2.memory[0]:
rg1 = binary_sum(rg1, rg3)
rg2.left_shift()
rg3.right_shift()
return BasicRegister(list(rg1.memory)[:-1])