Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen der Seite angezeigt.
| Beide Seiten, vorherige Überarbeitung Vorherige Überarbeitung Nächste Überarbeitung | Vorherige Überarbeitung | ||
| gf_informatik:zahlensysteme:binary_solutions [2026-03-31 06:07] – [Umwandlung Dezimal-Binär] hof | gf_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 | ||
| - | < | + | < |
| ### Umwandlung Binär-Dezimal | ### Umwandlung Binär-Dezimal | ||
| Zeile 23: | Zeile 22: | ||
| 1. **Zwei separate Variablen**: | 1. **Zwei separate Variablen**: | ||
| 2. **Binärstring umkehren**, also aus `' | 2. **Binärstring umkehren**, also aus `' | ||
| - | | + | |
| <nodisp 1> | <nodisp 1> | ||
| ++++Lösung| | ++++Lösung| | ||
| - | < | + | < |
| + | def binary_to_decimal(b): | ||
| """ | """ | ||
| d = 0 | d = 0 | ||
| + | exponent = len(b) - 1 | ||
| for digit in b: | for digit in b: | ||
| - | d = d*2 | ||
| if digit == ' | if digit == ' | ||
| - | d = d + 1 | + | d = d + 2**exponent |
| + | exponent = exponent - 1 | ||
| return d | return d | ||
| - | print(binary_to_decimal(" | + | print(binary_to_decimal(" |
| + | </ | ||
| ++++ | ++++ | ||
| </ | </ | ||
| Zeile 44: | Zeile 46: | ||
| Der {{gf_informatik: | Der {{gf_informatik: | ||
| - | < | + | < |
| ++++Lösung| | ++++Lösung| | ||
| - | < | + | < |
| def decimal_to_binary(d): | def decimal_to_binary(d): | ||
| """ | """ | ||
| Zeile 72: | Zeile 74: | ||
| <nodisp 2> | <nodisp 2> | ||
| ++++Lösung| | ++++Lösung| | ||
| - | < | + | < |
| def fill_zeros(b, | def fill_zeros(b, | ||
| while len(b) < digits: | while len(b) < digits: | ||
| Zeile 111: | Zeile 113: | ||
| <nodisp 2> | <nodisp 2> | ||
| ++++Lösung| | ++++Lösung| | ||
| - | <code python> | + | <html>< |
| def invert(b): | def invert(b): | ||
| """ | """ | ||
| Zeile 137: | Zeile 139: | ||
| result = result[-stellen: | result = result[-stellen: | ||
| return result | return result | ||
| - | </code> | + | </bottom-editor></ |
| ++++ | ++++ | ||
| </ | </ | ||
| Zeile 145: | 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>< |
| a_dec = 42 | a_dec = 42 | ||
| b_dec = 19 | b_dec = 19 | ||
| Zeile 153: | Zeile 155: | ||
| difference_dec = binary_to_decimal(difference_bin) | difference_dec = binary_to_decimal(difference_bin) | ||
| print(f" | print(f" | ||
| - | </code> | + | </bottom-editor></ |
| Resultat: | Resultat: | ||