Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def add_2bit(bit1, bit2, carry=0):
- # Add two 1-bit numbers with a carry using add_binary
- bit1, bit2, carry = int(bit1), int(bit2), int(carry)
- sum_result = (bit1 + bit2 + carry) % 2
- carry = (bit1 + bit2 + carry) // 2
- return str(sum_result), str(carry)
- def add_3bit(num1, num2, carry=0):
- # Add three 1-bit numbers with a carry using add_2bit
- carry = int(carry)
- result, carry1 = add_2bit(num1, num2, carry)
- result, carry2 = add_2bit(result, '0', 0) # Always pass 0 as carry to the second add_2bit
- return result, str(int(carry1) or int(carry2))
- def add_binary(num1, num2):
- # Add two binary numbers using add_3bit
- sum_result = ""
- carry = 0
- for i in range(len(num1) - 1, -1, -1):
- bit, carry = add_3bit(num1[i], num2[i], carry)
- sum_result = bit + sum_result
- if carry:
- sum_result = str(carry) + sum_result
- return sum_result
- Benutzereingabe
- binary1 = input("Geben Sie die erste Binärzahl ein: ")
- binary2 = input("Geben Sie die zweite Binärzahl ein: ")
- Ergebnis ausgeben
- ergebnis = add_binary(binary1, binary2)
- print(f'Die Summe von {binary1} und {binary2} ist {ergebnis}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement