CCCPaste

compile_s7_format

import re
import struct

def compile_s7_format(fmt):
    s7_fmt = ">"
    current_size = 0

    for match in re.finditer(r"(\d*)([a-zA-Z])", fmt):
        count_str, dtype = match.groups()
        count = int(count_str) if count_str else 1
        
        # 1. Sonderfall: Füllbytes (x) direkt unverändert anhängen
        if dtype == "x":
            s7_fmt += f"{count}x"
            current_size += count
            continue

        # 2. Alignment berechnen
        ssize = struct.calcsize(f">{dtype}")
        if (remainder := current_size % ssize) != 0:
            padding_bytes = ssize - remainder
            s7_fmt += f"{padding_bytes}x"
            current_size += padding_bytes

        # 3. Den originalen Typ formschlüssig anhängen
        # Wichtig: Nutzen Sie das originale count_str, um 'f' statt '1f' zu schreiben
        s7_fmt += f"{count_str}{dtype}"
        current_size += ssize * count

    return s7_fmt