Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen der Seite angezeigt.
Nächste Überarbeitung | Vorherige Überarbeitung | ||
gf_informatik:zahlensysteme:binary_solutions [2025-05-05 12:42] – angelegt hof | gf_informatik:zahlensysteme:binary_solutions [2025-05-17 08:12] (aktuell) – [Ausprobieren] hof | ||
---|---|---|---|
Zeile 29: | Zeile 29: | ||
print(decimal_to_binary(42))</ | print(decimal_to_binary(42))</ | ||
+ | ### Binär-Addition | ||
+ | < | ||
+ | while len(b) < digits: | ||
+ | b = " | ||
+ | return b | ||
+ | def binary_add(a, | ||
+ | """ | ||
+ | n = max(len(a), len(b)) | ||
+ | a = fill_zeros(a, | ||
+ | b = fill_zeros(b, | ||
+ | | ||
+ | out = "" | ||
+ | carry = 0 | ||
+ | index = n - 1 | ||
+ | while index >= 0: | ||
+ | digit_a = int(a[index]) | ||
+ | digit_b = int(b[index]) | ||
+ | sum = digit_a + digit_b + carry | ||
+ | if sum == 0: | ||
+ | out = " | ||
+ | carry = 0 | ||
+ | elif sum == 1: | ||
+ | out = " | ||
+ | carry = 0 | ||
+ | elif sum == 2: | ||
+ | out = " | ||
+ | carry = 1 | ||
+ | elif sum == 1: | ||
+ | out = " | ||
+ | carry = 1 | ||
+ | index = index - 1 | ||
+ | if carry != 0: | ||
+ | out = str(carry) + out | ||
+ | return out | ||
+ | |||
+ | print(binary_add(" | ||
+ | ### Binär-Subtraktion | ||
+ | |||
+ | <code python> | ||
+ | def invert(b): | ||
+ | """ | ||
+ | result = "" | ||
+ | for digit in b: | ||
+ | if digit == " | ||
+ | result = result + " | ||
+ | else: | ||
+ | result = result + " | ||
+ | return result | ||
+ | |||
+ | def zweierkomplement(b, | ||
+ | """ | ||
+ | # 1) Auffüllen auf stellen bits | ||
+ | b = fill_zeros(b, | ||
+ | # 2) Invertieren (1->0, 0->1) | ||
+ | b = invert(b) | ||
+ | # 3) Addiere 1 | ||
+ | return binary_add(b, | ||
+ | |||
+ | def binary_subtraction(a, | ||
+ | """ | ||
+ | complement = zweierkomplement(b, | ||
+ | result = binary_add(a, | ||
+ | result = result[-stellen: | ||
+ | return result | ||
+ | </ | ||
+ | |||
+ | ### Ausprobieren | ||
+ | |||
+ | Kopiere alle Funktionen oben in die gleiche Python-Datei. Überprüfe danach die Funktionsweise: | ||
+ | |||
+ | <code python> | ||
+ | a_dec = 42 | ||
+ | b_dec = 19 | ||
+ | a_bin = decimal_to_binary(a_dec) | ||
+ | b_bin = decimal_to_binary(b_dec) | ||
+ | difference_bin = binary_subtraction(a_bin, | ||
+ | difference_dec = binary_to_decimal(difference_bin) | ||
+ | print(f" | ||
+ | </ | ||
+ | |||
+ | Resultat: | ||
+ | < | ||
+ | 42 - 19 = 101010 - 10011 = 00010111 = 23 | ||
+ | </ | ||