diff --git a/bitutilities.py b/bitutilities.py index 079e660..fdcfeb6 100644 --- a/bitutilities.py +++ b/bitutilities.py @@ -67,46 +67,44 @@ def get_memory(variable_name: str) -> list[bool]: print(f"[ERROR] The {variable_name} may contain only 1-s and 0-s!") -def binary_sum(first_term: BasicRegister, second_term: BasicRegister, return_remainder: bool = False) \ - -> BasicRegister or tuple[BasicRegister, int]: - """ - Sums two registers' values. - - :param BasicRegister first_term: First register. - :param BasicRegister second_term: Second register. - :param bool return_remainder: True to return the tuple, False to return just the register. - - :return: Register containing the sum or the tuple containing the register and carried radix. - :rtype: BasicRegister | tuple[BasicRegister, int] - """ - result = BasicRegister([False] * len(first_term)) +def binary_sum_with_carry(first_term: BasicRegister, second_term: BasicRegister) -> tuple[BasicRegister, int]: + result_term = BasicRegister([False] * len(first_term)) carry = False for i in range(len(first_term) - 1, 0, -1): current_bit_sum = first_term.memory[i] + second_term.memory[i] + carry carry = bool(current_bit_sum & 2) - result.memory[i] = bool(current_bit_sum & 1) + result_term.memory[i] = bool(current_bit_sum & 1) final_bit_sum = first_term.memory[0] + second_term.memory[0] + carry - result.memory[0] = bool(final_bit_sum & 1) + final_carry = bool(final_bit_sum & 2) + result_term.memory[0] = bool(final_bit_sum & 1) - if return_remainder: - final_carry = bool(final_bit_sum & 2) - return result, final_carry - else: - return result + return result_term, final_carry + + +def binary_sum(first_term: BasicRegister, second_term: BasicRegister) -> BasicRegister: + """ + Sums two registers' values. + + :param BasicRegister first_term: First register. + :param BasicRegister second_term: Second register. + + :return: Register containing the sum or the tuple containing the register and carried radix. + :rtype: BasicRegister | tuple[BasicRegister, int] + """ + return binary_sum_with_carry(first_term, second_term)[0] def binary_subtraction(first_term: BasicRegister, second_term: BasicRegister) -> BasicRegister: - second_term.reverse() result: BasicRegister final_carry: bool - result, final_carry = binary_sum(first_term, second_term, True) + result, final_carry = binary_sum_with_carry(first_term, second_term) if final_carry: - return binary_sum(result, BasicRegister([True] * len(result))) + return binary_sum(result, BasicRegister([False] * (len(result) - 1) + [True])) else: result.reverse() return result