Advertisement
Guest User

Binär Rechner

a guest
Dec 4th, 2023
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | Source Code | 0 0
  1. def add_2bit(bit1, bit2, carry=0):
  2.     # Add two 1-bit numbers with a carry using add_binary
  3.     bit1, bit2, carry = int(bit1), int(bit2), int(carry)
  4.     sum_result = (bit1 + bit2 + carry) % 2
  5.     carry = (bit1 + bit2 + carry) // 2
  6.     return str(sum_result), str(carry)
  7.  
  8. def add_3bit(num1, num2, carry=0):
  9.     # Add three 1-bit numbers with a carry using add_2bit
  10.     carry = int(carry)
  11.     result, carry1 = add_2bit(num1, num2, carry)
  12.     result, carry2 = add_2bit(result, '0', 0)  # Always pass 0 as carry to the second add_2bit
  13.     return result, str(int(carry1) or int(carry2))
  14.  
  15. def add_binary(num1, num2):
  16.     # Add two binary numbers using add_3bit
  17.     sum_result = ""
  18.     carry = 0
  19.     for i in range(len(num1) - 1, -1, -1):
  20.         bit, carry = add_3bit(num1[i], num2[i], carry)
  21.         sum_result = bit + sum_result
  22.  
  23.     if carry:
  24.         sum_result = str(carry) + sum_result
  25.  
  26.     return sum_result
  27.  
  28. Benutzereingabe
  29. binary1 = input("Geben Sie die erste Binärzahl ein: ")
  30. binary2 = input("Geben Sie die zweite Binärzahl ein: ")
  31.  
  32. Ergebnis ausgeben
  33. ergebnis = add_binary(binary1, binary2)
  34. print(f'Die Summe von {binary1} und {binary2} ist {ergebnis}')
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement