Zahlensysteme: Binär, Hexadezimal, Dezimal & Bit-Operationen
Dieser Beitrag ist eine umfassende Einführung in die Zahlensysteme – inklusive Binär, Hexadezimal, Dezimal, Umrechnung und Bit-Operationen mit praktischen Beispielen.
In a Nutshell
Computer verwenden Binärsysteme (0 und 1). Hexadezimal dient als kompakte Darstellung für Binärwerte. Bit-Operationen ermöglichen direkte Manipulation von Daten auf Bitebene.
Kompakte Fachbeschreibung
Zahlensysteme sind Methoden zur Darstellung von Zahlen mit unterschiedlichen Basen. Computer verwenden intern das Binärsystem (Basis 2), während Menschen das Dezimalsystem (Basis 10) bevorzugen.
Wichtige Zahlensysteme:
Dezimalsystem (Basis 10)
- Ziffern: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
- Stellenwerte: 10⁰, 10¹, 10², 10³, …
- Verwendung: Menschliche Kommunikation, Alltagsmathematik
- Beispiel: 123 = 1×10² + 2×10¹ + 3×10⁰
Binärsystem (Basis 2)
- Ziffern: 0, 1
- Stellenwerte: 2⁰, 2¹, 2², 2³, …
- Verwendung: Computerinterne Darstellung
- Beispiel: 1011 = 1×2³ + 0×2² + 1×2¹ + 1×2⁰ = 11
Hexadezimalsystem (Basis 16)
- Ziffern: 0-9, A, B, C, D, E, F
- Stellenwerte: 16⁰, 16¹, 16², 16³, …
- Verwendung: Kompakte Binärdarstellung, Farben, Speicheradressen
- Beispiel: A3 = 10×16¹ + 3×16⁰ = 163
Oktalsystem (Basis 8)
- Ziffern: 0, 1, 2, 3, 4, 5, 6, 7
- Stellenwerte: 8⁰, 8¹, 8², 8³, …
- Verwendung: Historisch in Unix-Systemen
- Beispiel: 75 = 7×8¹ + 5×8⁰ = 61
Prüfungsrelevante Stichpunkte
- Dezimalsystem: Basis 10, Ziffern 0-9, Stellenwerte 10ⁿ
- Binärsystem: Basis 2, Ziffern 0-1, Computerdarstellung
- Hexadezimalsystem: Basis 16, Ziffern 0-9, A-F, kompakte Darstellung
- Umrechnung: Division/Multiplikation mit Basis, Stellenwertmethode
- Bit-Operationen: AND, OR, XOR, NOT, Shift-Operationen
- Zweierkomplement: Negative Zahlen im Binärsystem
- IHK-relevant: Grundlage für Computerarchitektur und Programmierung
Kernkomponenten
- Zahlensysteme: Dezimal, Binär, Hexadezimal, Oktal
- Umrechnung: Zwischen verschiedenen Basen
- Bit-Operationen: AND, OR, XOR, NOT, Shift
- Zweierkomplement: Negative Zahlen
- Computerarithmetik: Addition, Subtraktion, Multiplikation
- Datentypen: Bits, Bytes, Words
- Speicherdarstellung: Hexadezimale Adressen
- Fehlererkennung: Parität, Checksummen
Praxisbeispiele
1. Umrechnung zwischen Zahlensystemen
public class ZahlensystemUmrechnung {
// Dezimal zu Binär
public static String dezimalZuBinaer(int dezimal) {
if (dezimal == 0) return "0";
StringBuilder binaer = new StringBuilder();
while (dezimal > 0) {
binaer.append(dezimal % 2);
dezimal /= 2;
}
return binaer.reverse().toString();
}
// Binär zu Dezimal
public static int binaerZuDezimal(String binaer) {
int dezimal = 0;
int potenz = 0;
for (int i = binaer.length() - 1; i >= 0; i--) {
if (binaer.charAt(i) == '1') {
dezimal += Math.pow(2, potenz);
}
potenz++;
}
return dezimal;
}
// Dezimal zu Hexadezimal
public static String dezimalZuHex(int dezimal) {
if (dezimal == 0) return "0";
char[] hexZiffern = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuilder hex = new StringBuilder();
while (dezimal > 0) {
int rest = dezimal % 16;
hex.append(hexZiffern[rest]);
dezimal /= 16;
}
return hex.reverse().toString();
}
// Hexadezimal zu Dezimal
public static int hexZuDezimal(String hex) {
int dezimal = 0;
String hexZiffern = "0123456789ABCDEF";
for (int i = 0; i < hex.length(); i++) {
char ziffer = hex.charAt(i);
int wert = hexZiffern.indexOf(ziffer);
dezimal = dezimal * 16 + wert;
}
return dezimal;
}
// Binär zu Hexadezimal
public static String binaerZuHex(String binaer) {
// Binär in 4er-Gruppen aufteilen
while (binaer.length() % 4 != 0) {
binaer = "0" + binaer;
}
StringBuilder hex = new StringBuilder();
for (int i = 0; i < binaer.length(); i += 4) {
String nibble = binaer.substring(i, i + 4);
int wert = binaerZuDezimal(nibble);
hex.append(dezimalZuHex(wert));
}
return hex.toString();
}
// Hexadezimal zu Binär
public static String hexZuBinaer(String hex) {
String[] binaerMap = {
"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"
};
StringBuilder binaer = new StringBuilder();
for (int i = 0; i < hex.length(); i++) {
char ziffer = hex.charAt(i);
int wert = "0123456789ABCDEF".indexOf(ziffer);
binaer.append(binaerMap[wert]);
}
// Führende Nullen entfernen
while (binaer.length() > 1 && binaer.charAt(0) == '0') {
binaer.deleteCharAt(0);
}
return binaer.toString();
}
public static void main(String[] args) {
int zahl = 175;
System.out.println("Zahl: " + zahl);
System.out.println("Binär: " + dezimalZuBinaer(zahl));
System.out.println("Hex: " + dezimalZuHex(zahl));
String binaer = "10101111";
String hex = "AF";
System.out.println("\nBinär " + binaer + " = Dezimal " + binaerZuDezimal(binaer));
System.out.println("Hex " + hex + " = Dezimal " + hexZuDezimal(hex));
System.out.println("Binär " + binaer + " = Hex " + binaerZuHex(binaer));
System.out.println("Hex " + hex + " = Binär " + hexZuBinaer(hex));
}
}
2. Bit-Operationen in verschiedenen Sprachen
// Java Bit-Operationen
public class BitOperationen {
public static void main(String[] args) {
int a = 12; // 1100 in Binär
int b = 10; // 1010 in Binär
System.out.println("a = " + a + " (Binär: " + Integer.toBinaryString(a) + ")");
System.out.println("b = " + b + " (Binär: " + Integer.toBinaryString(b) + ")");
// Bitweises AND (&)
int and = a & b; // 1100 & 1010 = 1000 (8)
System.out.println("a & b = " + and + " (Binär: " + Integer.toBinaryString(and) + ")");
// Bitweises OR (|)
int or = a | b; // 1100 | 1010 = 1110 (14)
System.out.println("a | b = " + or + " (Binär: " + Integer.toBinaryString(or) + ")");
// Bitweises XOR (^)
int xor = a ^ b; // 1100 ^ 1010 = 0110 (6)
System.out.println("a ^ b = " + xor + " (Binär: " + Integer.toBinaryString(xor) + ")");
// Bitweises NOT (~)
int notA = ~a; // ~1100 = 0011 (mit Zweierkomplement)
System.out.println("~a = " + notA + " (Binär: " + Integer.toBinaryString(notA) + ")");
// Left Shift (<<)
int leftShift = a << 2; // 1100 << 2 = 110000 (48)
System.out.println("a << 2 = " + leftShift + " (Binär: " + Integer.toBinaryString(leftShift) + ")");
// Right Shift (>>)
int rightShift = a >> 1; // 1100 >> 1 = 0110 (6)
System.out.println("a >> 1 = " + rightShift + " (Binär: " + Integer.toBinaryString(rightShift) + ")");
// Unsigned Right Shift (>>>)
int unsignedRightShift = a >>> 1; // 1100 >>> 1 = 0110 (6)
System.out.println("a >>> 1 = " + unsignedRightShift + " (Binär: " + Integer.toBinaryString(unsignedRightShift) + ")");
// Praktische Anwendungen
praktischeAnwendungen();
}
private static void praktischeAnwendungen() {
System.out.println("\n=== Praktische Anwendungen ===");
// Bit prüfen (ist das 3. Bit gesetzt?)
int zahl = 12; // 1100
int bitPosition = 2;
boolean bitSet = (zahl & (1 << bitPosition)) != 0;
System.out.println("Bit " + bitPosition + " in " + zahl + " gesetzt: " + bitSet);
// Bit setzen
int mitBit = zahl | (1 << bitPosition);
System.out.println("Setze Bit " + bitPosition + ": " + mitBit);
// Bit löschen
int ohneBit = zahl & ~(1 << bitPosition);
System.out.println("Lösche Bit " + bitPosition + ": " + ohneBit);
// Bit umschalten (toggle)
int umgeschaltet = zahl ^ (1 << bitPosition);
System.out.println("Umschalte Bit " + bitPosition + ": " + umgeschaltet);
// Farbe aus RGB-Werten extrahieren
int farbe = 0xFF6B35; // Orange
int rot = (farbe >> 16) & 0xFF;
int gruen = (farbe >> 8) & 0xFF;
int blau = farbe & 0xFF;
System.out.println("\nFarbe: #" + Integer.toHexString(farbe).toUpperCase());
System.out.println("Rot: " + rot);
System.out.println("Grün: " + gruen);
System.out.println("Blau: " + blau);
}
}
3. Zweierkomplement für negative Zahlen
public class Zweierkomplement {
// Zweierkomplement berechnen
public static String zweierkomplement(int zahl, int bits) {
if (zahl >= 0) {
return String.format("%" + bits + "s", Integer.toBinaryString(zahl)).replace(' ', '0');
}
// Negative Zahl: 2^bits - |zahl|
int positiv = (int) (Math.pow(2, bits) + zahl);
return String.format("%" + bits + "s", Integer.toBinaryString(positiv)).replace(' ', '0');
}
// Aus Zweierkomplement Dezimalwert berechnen
public static int vonZweierkomplement(String binaer) {
int bits = binaer.length();
// Wenn höchstes Bit 0 ist, positive Zahl
if (binaer.charAt(0) == '0') {
return Integer.parseInt(binaer, 2);
}
// Negative Zahl: - (2^bits - wert)
int wert = Integer.parseInt(binaer, 2);
return wert - (int) Math.pow(2, bits);
}
public static void main(String[] args) {
int[] zahlen = {13, 5, 0, -1, -5, -13};
int bits = 8;
System.out.println("Zweierkomplement mit " + bits + " Bits:");
System.out.println("Zahl\tBinär\t\tDezimal");
System.out.println("----\t----\t\t-------");
for (int zahl : zahlen) {
String binaer = zweierkomplement(zahl, bits);
System.out.println(zahl + "\t" + binaer + "\t" + vonZweierkomplement(binaer));
}
// Bereichsanzeige
System.out.println("\nBereich bei " + bits + " Bits:");
System.out.println("Minimum: " + (-(int) Math.pow(2, bits-1)));
System.out.println("Maximum: " + ((int) Math.pow(2, bits-1) - 1));
// Überlauf demonstrieren
System.out.println("\nÜberlauf-Demonstration:");
int max = (int) Math.pow(2, bits-1) - 1;
int ueberlauf = max + 1;
System.out.println("Max: " + max + " -> " + zweierkomplement(max, bits));
System.out.println("Max+1: " + ueberlauf + " -> " + zweierkomplement(ueberlauf, bits));
System.out.println("Erwartet: " + (-(int) Math.pow(2, bits-1)) + " -> " + zweierkomplement(-(int) Math.pow(2, bits-1), bits));
}
}
4. Computerarithmetik
public class Computerarithmetik {
// Binäre Addition
public static String binaerAddition(String a, String b) {
int laenge = Math.max(a.length(), b.length());
// Mit führenden Nullen auffüllen
a = String.format("%" + laenge + "s", a).replace(' ', '0');
b = String.format("%" + laenge + "s", b).replace(' ', '0');
StringBuilder ergebnis = new StringBuilder();
int carry = 0;
// Von rechts nach links addieren
for (int i = laenge - 1; i >= 0; i--) {
int summe = carry + (a.charAt(i) - '0') + (b.charAt(i) - '0');
ergebnis.append(summe % 2);
carry = summe / 2;
}
// Carry am Ende hinzufügen
if (carry > 0) {
ergebnis.append(carry);
}
return ergebnis.reverse().toString();
}
// Binäre Subtraktion (Zweierkomplement-Methode)
public static String binaerSubtraktion(String a, String b) {
// b negieren (Zweierkomplement)
String negiert = zweierkomplementNegieren(b);
// a + (-b)
return binaerAddition(a, negiert);
}
private static String zweierkomplementNegieren(String binaer) {
// Bits invertieren
StringBuilder invertiert = new StringBuilder();
for (char bit : binaer.toCharArray()) {
invertiert.append(bit == '0' ? '1' : '0');
}
// 1 addieren
return binaerAddition(invertiert.toString(), "1");
}
// Binäre Multiplikation
public static String binaerMultiplikation(String a, String b) {
int aDez = Integer.parseInt(a, 2);
int bDez = Integer.parseInt(b, 2);
int produkt = aDez * bDez;
return Integer.toBinaryString(produkt);
}
// Feste-Punkt-Arithmetik
public static double festePunktAddition(double a, double b, int nachkommastellen) {
int faktor = (int) Math.pow(10, nachkommastellen);
int aInt = (int) Math.round(a * faktor);
int bInt = (int) Math.round(b * faktor);
int ergebnisInt = aInt + bInt;
return (double) ergebnisInt / faktor;
}
// Gleitkomma-Darstellung (vereinfacht)
public static void gleitkommaDarstellung(double zahl) {
if (zahl == 0) {
System.out.println("0 = 0.0 × 2^0");
return;
}
boolean negativ = zahl < 0;
zahl = Math.abs(zahl);
int exponent = 0;
// Normalisieren
while (zahl >= 2.0) {
zahl /= 2.0;
exponent++;
}
while (zahl < 1.0) {
zahl *= 2.0;
exponent--;
}
System.out.println((negativ ? "-" : "") + zahl + " × 2^" + exponent);
}
public static void main(String[] args) {
System.out.println("=== Binäre Arithmetik ===");
String a = "1011"; // 11
String b = "1101"; // 13
System.out.println("a = " + a + " (" + Integer.parseInt(a, 2) + ")");
System.out.println("b = " + b + " (" + Integer.parseInt(b, 2) + ")");
String summe = binaerAddition(a, b);
System.out.println("a + b = " + summe + " (" + Integer.parseInt(summe, 2) + ")");
String differenz = binaerSubtraktion(b, a);
System.out.println("b - a = " + differenz + " (" + Integer.parseInt(differenz, 2) + ")");
String produkt = binaerMultiplikation(a, b);
System.out.println("a × b = " + produkt + " (" + Integer.parseInt(produkt, 2) + ")");
System.out.println("\n=== Feste-Punkt-Arithmetik ===");
double x = 12.34;
double y = 5.67;
double summeFP = festePunktAddition(x, y, 2);
System.out.println(x + " + " + y + " = " + summeFP + " (2 Nachkommastellen)");
System.out.println("\n=== Gleitkomma-Darstellung ===");
double[] zahlen = {12.5, 0.75, -3.125, 256.0};
for (double zahl : zahlen) {
System.out.print(zahl + " = ");
gleitkommaDarstellung(zahl);
}
}
}
5. Python Bit-Operationen und Zahlensysteme
# Python Zahlensysteme und Bit-Operationen
def dezimal_zu_binaer(dezimal):
"""Dezimal zu Binär umrechnen"""
if dezimal == 0:
return "0"
binaer = ""
while dezimal > 0:
binaer = str(dezimal % 2) + binaer
dezimal //= 2
return binaer
def binaer_zu_dezimal(binaer):
"""Binär zu Dezimal umrechnen"""
return int(binaer, 2)
def dezimal_zu_hex(dezimal):
"""Dezimal zu Hexadezimal umrechnen"""
hex_ziffern = "0123456789ABCDEF"
if dezimal == 0:
return "0"
hex = ""
while dezimal > 0:
hex = hex_ziffern[dezimal % 16] + hex
dezimal //= 16
return hex
def hex_zu_dezimal(hex):
"""Hexadezimal zu Dezimal umrechnen"""
return int(hex, 16)
def bit_operationen_demo():
"""Bit-Operationen demonstrieren"""
a = 12 # 1100
b = 10 # 1010
print(f"a = {a} (Binär: {bin(a)})")
print(f"b = {b} (Binär: {bin(b)})")
# Bitweises AND
and_result = a & b
print(f"a & b = {and_result} (Binär: {bin(and_result)})")
# Bitweises OR
or_result = a | b
print(f"a | b = {or_result} (Binär: {bin(or_result)})")
# Bitweises XOR
xor_result = a ^ b
print(f"a ^ b = {xor_result} (Binär: {bin(xor_result)})")
# Bitweises NOT
not_a = ~a
print(f"~a = {not_a} (Binär: {bin(not_a & 0xFFFFFFFF)})")
# Left Shift
left_shift = a << 2
print(f"a << 2 = {left_shift} (Binär: {bin(left_shift)})")
# Right Shift
right_shift = a >> 1
print(f"a >> 1 = {right_shift} (Binär: {bin(right_shift)})")
def farbe_aus_rgb(rot, gruen, blau):
"""RGB-Farbe als 24-Bit-Wert zusammenfassen"""
return (rot << 16) | (gruen << 8) | blau
def rgb_aus_farbe(farbe):
"""RGB-Komponenten aus 24-Bit-Farbe extrahieren"""
rot = (farbe >> 16) & 0xFF
gruen = (farbe >> 8) & 0xFF
blau = farbe & 0xFF
return rot, gruen, blau
def bit_manipulation_demo():
"""Bit-Manipulation demonstrieren"""
zahl = 0b10101000 # 168
print(f"Ursprüngliche Zahl: {zahl} (Binär: {bin(zahl)})")
# Bit prüfen
bit_position = 3
bit_gesetzt = (zahl & (1 << bit_position)) != 0
print(f"Bit {bit_position} gesetzt: {bit_gesetzt}")
# Bit setzen
mit_bit = zahl | (1 << bit_position)
print(f"Setze Bit {bit_position}: {mit_bit} (Binär: {bin(mit_bit)})")
# Bit löschen
ohne_bit = zahl & ~(1 << bit_position)
print(f"Lösche Bit {bit_position}: {ohne_bit} (Binär: {bin(ohne_bit)})")
# Bit umschalten
umgeschaltet = zahl ^ (1 << bit_position)
print(f"Umschalte Bit {bit_position}: {umgeschaltet} (Binär: {bin(umgeschaltet)})")
def hauptprogramm():
"""Hauptprogramm mit allen Demonstrationen"""
print("=== Zahlensysteme Umrechnung ===")
zahl = 175
print(f"Dezimal {zahl}:")
print(f" Binär: {dezimal_zu_binaer(zahl)}")
print(f" Hex: {dezimal_zu_hex(zahl)}")
print("\n=== Bit-Operationen ===")
bit_operationen_demo()
print("\n=== Bit-Manipulation ===")
bit_manipulation_demo()
print("\n=== Farben als RGB ===")
orange = farbe_aus_rgb(255, 107, 53)
print(f"Orange: #{orange:06X}")
r, g, b = rgb_aus_farbe(orange)
print(f"RGB: ({r}, {g}, {b})")
print("\n=== Zweierkomplement (8-Bit) ===")
for i in range(-5, 6):
if i >= 0:
binaer = format(i, '08b')
else:
binaer = format((256 + i), '08b')
print(f"{i:3d}: {binaer}")
if __name__ == "__main__":
hauptprogramm()
Umrechnungstabelle
| Dezimal | Binär | Hexadezimal | Oktal |
|---|---|---|---|
| 0 | 0000 | 0 | 0 |
| 1 | 0001 | 1 | 1 |
| 2 | 0010 | 2 | 2 |
| 3 | 0011 | 3 | 3 |
| 4 | 0100 | 4 | 4 |
| 5 | 0101 | 5 | 5 |
| 6 | 0110 | 6 | 6 |
| 7 | 0111 | 7 | 7 |
| 8 | 1000 | 8 | 10 |
| 9 | 1001 | 9 | 11 |
| 10 | 1010 | A | 12 |
| 11 | 1011 | B | 13 |
| 12 | 1100 | C | 14 |
| 13 | 1101 | D | 15 |
| 14 | 1110 | E | 16 |
| 15 | 1111 | F | 17 |
Bit-Operationen Übersicht
| Operator | Symbol | Beschreibung | Beispiel |
|----------|--------|-------------|----------|
| AND | & | Bitweises UND | 5 & 3 = 1 |
| OR | \| | Bitweises ODER | 5 \| 3 = 7 |
| XOR | ^ | Exklusives ODER | 5 ^ 3 = 6 |
| NOT | ~ | Bitweises NICHT | ~5 = -6 |
| Left Shift | << | Links verschieben | 5 << 2 = 20 |
| Right Shift | >> | Rechts verschieben | 5 >> 1 = 2 |
| Unsigned Right Shift | >>> | Vorzeichenloses Rechtsverschieben | 5 >>> 1 = 2 |
Speichergrößen
| Einheit | Bytes | Bits | Bereich (unsigned) |
|---|---|---|---|
| Byte | 1 | 8 | 0 - 255 |
| Word | 2 | 16 | 0 - 65,535 |
| DWord | 4 | 32 | 0 - 4,294,967,295 |
| QWord | 8 | 64 | 0 - 18,446,744,073,709,551,615 |
Zweierkomplement Bereich
| Bits | Minimum | Maximum |
|---|---|---|
| 8 | -128 | 127 |
| 16 | -32,768 | 32,767 |
| 32 | -2,147,483,648 | 2,147,483,647 |
| 64 | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
Vorteile und Nachteile
Vorteile von Binärsystem
- Einfach: Nur zwei Zustände (0 und 1)
- Zuverlässig: Leicht fehlerfrei zu implementieren
- Effizient: Optimal für elektronische Schaltungen
- Universell: Grundlage aller digitaler Systeme
Vorteile von Hexadezimalsystem
- Kompakt: 4 Binärziffern = 1 Hexziffer
- Lesbar: Kürzer und übersichtlicher als Binär
- Standard: Weit verbreitet in der Programmierung
- Praktisch: Ideal für Adressen und Farben
Nachteile
- Abstraktion: Nicht intuitiv für Menschen
- Umrechnung: Erfordert mentale Arithmetik
- Fehleranfällig: Leicht bei manueller Umrechnung
Häufige Prüfungsfragen
1. **Wandeln Sie 175 (dezimal) in Binär und Hexadezimal um!**
175₁₀ = 10101111₂ = AF₁₆
2. **Was ist das Ergebnis von 12 & 10 (bitweises AND)?**
12₁₀ = 1100₂, 10₁₀ = 1010₂ → 1100 & 1010 = 1000₂ = 8₁₀
3. **Erklären Sie das Zweierkomplement!**
Methode zur Darstellung negativer Zahlen im Binärsystem durch Bit-Inversion und Addition von 1.
4. **Wofür werden Hexadezimalzahlen verwendet?**
Kompakte Darstellung von Binärwerten, Farben, Speicheradressen, Fehlercodes.
Wichtigste Quellen
- https://de.wikipedia.org/wiki/Zahlensystem
- https://de.wikipedia.org/wiki/Zweierkomplement
- https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html