Created
March 7, 2025 11:51
-
-
Save Jan-Zeiseweis/441e6f5571991f467c6949b5bc4e34a1 to your computer and use it in GitHub Desktop.
Data Unit Converter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
# Umrechnungsfaktoren | |
BIN_PREFIX = {"ki": 1024, "mi": 1024**2, "gi": 1024**3, "ti": 1024**4, | |
"pi": 1024**5, "ei": 1024**6, "zi": 1024**7, "yi": 1024**8} | |
DEC_PREFIX = {"k": 1000, "m": 1000**2, "g": 1000**3, "t": 1000**4, | |
"p": 1000**5, "e": 1000**6, "z": 1000**7, "y": 1000**8} | |
# Regex zum Parsen der Eingabe | |
pattern = re.compile(r"^(\d+)([kmgtpezy]?i?)(bit|byte)$", re.IGNORECASE) | |
def parse_size(size_str): | |
"""Parst eine Speichergröße (z.B. '128kibit')""" | |
match = pattern.match(size_str.lower()) | |
if not match: | |
raise ValueError(f"Ungültige Eingabe: {size_str}") | |
value, prefix, unit = match.groups() | |
value = int(value) | |
factor = 1 | |
if prefix in BIN_PREFIX: | |
factor = BIN_PREFIX[prefix] | |
elif prefix in DEC_PREFIX: | |
factor = DEC_PREFIX[prefix] | |
if unit == "bit": | |
factor /= 8 # Umrechnung Bit → Byte | |
return value * factor # Rückgabe in Bytes | |
def convert_size(size_str, target_unit): | |
"""Konvertiert eine Größe in eine andere Einheit (z.B. '128kibit' → 'mbyte')""" | |
bytes_value = parse_size(size_str) | |
match = pattern.match(target_unit.lower()) | |
if not match: | |
raise ValueError(f"Ungültige Ziel-Einheit: {target_unit}") | |
_, target_prefix, target_unit_type = match.groups() | |
target_factor = 1 | |
if target_prefix in BIN_PREFIX: | |
target_factor = BIN_PREFIX[target_prefix] | |
elif target_prefix in DEC_PREFIX: | |
target_factor = DEC_PREFIX[target_prefix] | |
if target_unit_type == "bit": | |
target_factor /= 8 # Umrechnung Byte → Bit | |
return bytes_value / target_factor | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment