DeaD_EyE

compile_s7_format

Aug 23rd, 2026
6,133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. import re
  2. import struct
  3.  
  4. def compile_s7_format(fmt):
  5.     s7_fmt = ">"
  6.     current_size = 0
  7.  
  8.     for match in re.finditer(r"(\d*)([a-zA-Z])", fmt):
  9.         count_str, dtype = match.groups()
  10.         count = int(count_str) if count_str else 1
  11.        
  12.         # 1. Sonderfall: Füllbytes (x) direkt unverändert anhängen
  13.         if dtype == "x":
  14.             s7_fmt += f"{count}x"
  15.             current_size += count
  16.             continue
  17.  
  18.         # 2. Alignment berechnen
  19.         ssize = struct.calcsize(f">{dtype}")
  20.         if (remainder := current_size % ssize) != 0:
  21.             padding_bytes = ssize - remainder
  22.             s7_fmt += f"{padding_bytes}x"
  23.             current_size += padding_bytes
  24.  
  25.         # 3. Den originalen Typ formschlüssig anhängen
  26.         # Wichtig: Nutzen Sie das originale count_str, um 'f' statt '1f' zu schreiben
  27.         s7_fmt += f"{count_str}{dtype}"
  28.         current_size += ssize * count
  29.  
  30.     return s7_fmt
  31.  
Advertisement
Add Comment
Please, Sign In to add comment