From d25dacf35b63ce9e2c4be199b034bf4ef24cd2cd Mon Sep 17 00:00:00 2001 From: dymik739 Date: Mon, 26 Jun 2023 21:05:45 +0300 Subject: [PATCH] add sum function for addition of two registers --- bitutilities.py | 40 ++++++++++++++++++++++++++++++++++++++++ main.py | 6 ++++++ 2 files changed, 46 insertions(+) diff --git a/bitutilities.py b/bitutilities.py index ff9adbe..20f84ec 100644 --- a/bitutilities.py +++ b/bitutilities.py @@ -27,6 +27,10 @@ class BasicRegister: shifted_radices: deque[bool] = deque([self.memory.pop() for _i in range(steps_shifted)]) return shifted_radices + def adjust_size(self, s: int) -> None: + current_memory_size: int = len(self.memory) + return BasicRegister([False] * max(s - current_memory_size, 0) + list(self.memory)[-current_memory_size:]) + def get_memory(variable_name: str) -> list[bool]: """ @@ -44,3 +48,39 @@ def get_memory(variable_name: str) -> list[bool]: 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 sum(a_original: BasicRegister, b_original: BasicRegister) -> BasicRegister: + """ + Sums two registers' values. + + :param BasicRegister a: First register. + :param BasicRegister b: Second register. + + :return: Register containing the result. + :rtype: BasicRegister + """ + size_a = len(a_original.memory) + size_b = len(b_original.memory) + + required_size = max(size_a, size_b) + + if size_a != size_b: + a = a_original.adjust_size(required_size) + b = b_original.adjust_size(required_size) + else: + a = a_original + b = b_original + + c = BasicRegister([False] * required_size) + + carry = False + for i in range(size_a - 1, 0, -1): + current_bit_sum = a.memory[i] + b.memory[i] + carry + carry = bool(current_bit_sum & 2) + c.memory[i] = bool(current_bit_sum & 1) + + final_bit_sum = a.memory[0] + b.memory[0] + carry + c.memory[0] = bool(final_bit_sum & 1) + + return c diff --git a/main.py b/main.py index 1e06d59..d1515d5 100644 --- a/main.py +++ b/main.py @@ -20,3 +20,9 @@ if __name__ == '__main__': print("\nShifted right:") print([int(value) for value in reg.right_shift()]) print(reg) + + reg2: BasicRegister = BasicRegister(get_memory("more memory")) + + reg3: BasicRegister = sum(reg, reg2) + + print(reg3)