Unterschiede

Hier werden die Unterschiede zwischen zwei Versionen der Seite angezeigt.

Link zu der Vergleichsansicht

Beide Seiten, vorherige Überarbeitung Vorherige Überarbeitung
Nächste Überarbeitung
Vorherige Überarbeitung
gf_informatik:zahlensysteme:binary_solutions [2026-03-31 05:32] hofgf_informatik:zahlensysteme:binary_solutions [2026-04-02 09:54] (aktuell) – [Umwandlung Dezimal-Binär] hof
Zeile 1: Zeile 1:
 ## Binärzahl-Operationen mit Python ## Binärzahl-Operationen mit Python
-<html><script type="module" src="https://bottom.ch/ksr/ed/bottom-editor.js"></script></html>+<html><script type="module" src="https://bottom.ch/editor/latest/bottom-editor.js"></script></html> 
 +### Umwandlung Binär-Dezimal
  
 +Nehmen wir `b = '101010'` als Beispiel. Jede Ziffer in diesem String steht an einer bestimmten Position:
 +^ Position  |  `0` |  `1` |  `2` |  `3` |  `4` |  `5` |
 +^ Ziffer    |  `1` |  `0` |  `1` |  `0` |  `1` |  `0` |
  
-### Umwandlung Binär-Dezimal+Um die Binärzahl in eine Dezimalzahl umzurechnen, müssen wir potenzieren: 
 +$$1 \cdot 2^\color{red}{5} + 0 \cdot 2^\color{red}{4} + 1 \cdot 2^\color{red}{3} + 0 \cdot 2^\color{red}{2} + 1 \cdot 2^\color{red}{1} + 0 \cdot 2^\color{red}{0}$$ 
 + 
 +Zu jeder Ziffer gehört also die passende Zweierpotenz: 
 +^ Position  |  `0` |  `1` |  `2` |  `3` |  `4` |  `5` | 
 +^ Ziffer    |  `1` |   `0` |  `1` |  `0` |  `1` |  `0` | 
 +^ Exponent  |      `5` |   `4` |  `3` |  `2` |  `1` |  `0` | 
 +^ Potenz    |     `32` |  `16` |  `8` |  `4` |  `2` |  `1` | 
 + 
 +Die Schwierigkeit bei diesem Code ist, dass **Position und Exponent genau gegenteilig sind**: Die Position startet bei $0$ und zählt hoch, der Exponent startet bei $5$ und zählt herunter. 
 + 
 +Dieses Problem kann man unterschiedlich lösen. Zwei mögliche Ansätze sind: 
 + 
 +   1. **Zwei separate Variablen**: Eine für die Position und eine für den Exponenten. 
 +   2. **Binärstring umkehren**, also aus `'101010'` wird `'010101'`: Jetzt stimmen Position und Exponent überein. [[.:binary_collection#rueckwaerts|Hier]] hat es Ideen. 
 +   3. Das Zwischenresultat wird **fortlaufend mit 2 multipliziert**.
  
 <nodisp 1> <nodisp 1>
 ++++Lösung| ++++Lösung|
  
-<html><bottom-editor style="min-height: 6lh">def binary_to_decimal(b):+<html><bottom-editor session="page"> 
 +def binary_to_decimal(b):
     """Wandelt Binärzahl b in Dezimalzahl um."""     """Wandelt Binärzahl b in Dezimalzahl um."""
     d = 0     d = 0
 +    exponent = len(b) - 1
     for digit in b:     for digit in b:
-        d = d*+        if digit == '1': 
-        d + int(digit)+            d = d 2**exponent 
 +        exponent exponent - 1
     return d     return d
  
-print(binary_to_decimal("101010"))</bottom-editor></html>+print(binary_to_decimal("101010")) 
 +</bottom-editor></html>
 ++++ ++++
 </nodisp> </nodisp>
- 
 ### Umwandlung Dezimal-Binär ### Umwandlung Dezimal-Binär
  
-Restwertalgorithmus: +Der {{gf_informatik:gfif_zahlensysteme_dossier_hof.pdf#page.8|Restwertalgorithmus wird im Dossier}} erklärtWir bilden fortlaufend den Rest und den Ganzzahl-Quotienten. Der Algorithmus funktioniert übrigens für alle Basen! 
-<html><bottom-editor style="min-height: 6lh">def decimal_to_binary(d):+ 
 +<nodisp 1> 
 +++++Lösung| 
 +<html><bottom-editor session="page"> 
 +def decimal_to_binary(d):
     """Wandelt Dezimalzahl mit dem Restwertalgorithmus in Binärzahl um."""     """Wandelt Dezimalzahl mit dem Restwertalgorithmus in Binärzahl um."""
     b = ""     b = ""
     while d > 0:     while d > 0:
-        = d % 2+        rest = d % 2
         d = d // 2         d = d // 2
-        b = str(r) + b+        b = str(rest) + b
     return b     return b
  
-print(decimal_to_binary(42))</bottom-editor></html> +print(decimal_to_binary(42)) 
 +</bottom-editor></html> 
 +++++ 
 +</nodisp>
  
 ### Binär-Addition ### Binär-Addition
-<html><bottom-editor>def fill_zeros(b, digits):+Umsetzungsidee: 
 +  * Beide Strings paarweise [[gf_informatik:zahlensysteme:binary_collection#rueckwaerts|von rechts nach links]] durchlaufen. 
 +  * An jeder Position das Bit aus `a` und `b` sowie einen allfälligen Übertrag addieren. 
 +  * Das Resultat-Bit an der Position ist `1`, wenn die Summe `1` oder `3` ist, sonst `0`. 
 +    * Tipp: also genau das Resultat von `summe % 2`... 
 +  * Der Übertrag auf die nächste Stelle ist `1` wenn die Summe `2` oder `3` ist. 
 +    * Also genau dem Resultat von ...? 
 + 
 +<nodisp 2> 
 +++++Lösung| 
 +<html><bottom-editor session="page"> 
 +def fill_zeros(b, digits):
     while len(b) < digits:     while len(b) < digits:
         b = "0" + b         b = "0" + b
     return b     return b
-def binary_add(a,b):+ 
 +def binary_add(a, b):
     """Addiert zwei Binärzahlen beliebiger Länge."""     """Addiert zwei Binärzahlen beliebiger Länge."""
     n = max(len(a), len(b))     n = max(len(a), len(b))
Zeile 47: Zeile 87:
          
     out = ""     out = ""
-    carry = 0+    carry = 0  # Übertrag
     index = n - 1     index = n - 1
     while index >= 0:     while index >= 0:
Zeile 53: Zeile 93:
         digit_b = int(b[index])         digit_b = int(b[index])
         sum = digit_a + digit_b + carry         sum = digit_a + digit_b + carry
-        if sum == 0: +        bit = sum % 2 
-            out = "0" + out +        carry = sum // 
-            carry = 0 +        out = str(bit) + out 
-        elif sum == 1: +
-            out = "1" + out +
-            carry = +
-        elif sum == 2+
-            out = "0" + out +
-            carry = 1 +
-        elif sum == 1: +
-            out = "1" + out +
-            carry = 1+
         index = index - 1         index = index - 1
 +        
     if carry != 0:     if carry != 0:
         out = str(carry) + out         out = str(carry) + out
     return out     return out
  
-print(binary_add("101010", "10111"))</bottom-editor></html>+print(binary_add("101010", "10111")) 
 +</bottom-editor></html> 
 +++++ 
 +</nodisp> 
 + 
 ### Binär-Subtraktion ### Binär-Subtraktion
  
-<code python>+<nodisp 2> 
 +++++Lösung| 
 +<html><bottom-editor session="page">
 def invert(b): def invert(b):
     """Erstellt einen neuen String, wobei 0en und 1en vertauscht sind."""     """Erstellt einen neuen String, wobei 0en und 1en vertauscht sind."""
Zeile 99: Zeile 139:
     result = result[-stellen: # Vorderstes Bit auslassen     result = result[-stellen: # Vorderstes Bit auslassen
     return result     return result
-</code>+</bottom-editor></html> 
 +++++ 
 +</nodisp>
  
 ### Ausprobieren ### Ausprobieren
Zeile 105: Zeile 147:
 Kopiere alle Funktionen oben in die gleiche Python-Datei. Überprüfe danach die Funktionsweise: Kopiere alle Funktionen oben in die gleiche Python-Datei. Überprüfe danach die Funktionsweise:
  
-<code python>+<html><bottom-editor session="page">
 a_dec = 42 a_dec = 42
 b_dec = 19 b_dec = 19
Zeile 113: Zeile 155:
 difference_dec = binary_to_decimal(difference_bin) difference_dec = binary_to_decimal(difference_bin)
 print(f"{a_dec} - {b_dec} = {a_bin} - {b_bin} = {difference_bin} = {difference_dec}") print(f"{a_dec} - {b_dec} = {a_bin} - {b_bin} = {difference_bin} = {difference_dec}")
-</code>+</bottom-editor></html>
  
 Resultat: Resultat:
  • gf_informatik/zahlensysteme/binary_solutions.1774935140.txt.gz
  • Zuletzt geändert: 2026-03-31 05:32
  • von hof