Decoding a controller's binary variable files (the dumps a backup carries for its variable
Decoding a controller's binary variable files (the dumps a backup carries for its variable namespaces) produced plausible-looking garbage: numbers in the wrong places, strings cut short, and no way to tell an uninitialized variable from a real value.
Three assumptions that hold for one row and not for the file:
SHORT, BYTE); reading everything as 4 bytes shifts every field after the first narrow one. That is why numbers look random rather than absent — the reader stays in bounds and simply reads the wrong window.2 + roundup(maxlen + 1, 2), not 2 + maxlen. Off by one byte per string accumulates into full misalignment.0x7FFFFFFF, 0x7FFF and a NaN payload mean "uninitialized"; compared as numbers they are just very large or very odd, so an uninitialized BOOLEAN reads as true.The container is a compressed stream with a declared length — and it is structurally the same as the format the vendor's program files use, so the same decompressor applies. Reading the declared instance size and checking that the fields you decoded sum to it is the cheapest self-check: a width table that is wrong will not add up.
Drive the reader from the type table and normalise sentinels before comparing:
WIDTH = {"BYTE": 1, "SHORT": 2, "INT": 4, "REAL": 4, "BOOL": 4}
def stride_for_string(maxlen: int) -> int:
return 2 + ((maxlen + 1 + 1) // 2) * 2 # 2-byte length prefix, even padding
def read_scalar(buf, off, type_name):
w = WIDTH[type_name]
raw = buf[off:off + w]
if type_name == "BOOL":
value = int.from_bytes(raw, "big")
return (None if value == 0x7FFFFFFF else bool(value)), off + w # sentinel first
return int.from_bytes(raw, "big"), off + wThen validate against the vendor's own text export, per namespace, and report the leaf count. Measured on one backup: 3,982 / 38,472 / 3,698 / 8,554 leaves across four namespaces, all matching — a fixed-width reader matches far fewer and, worse, fails silently on the ones it "reads".
$ python3 decode.py --file sysmast.sv --compare vendor-export.txt
leaves 3982/3982 matched
instance size 0x1A40: decoded fields sum to 0x1A40 <- the width table is consistentIf the decoded fields do not sum to the declared instance size, the table still has a wrong entry — that check catches the misalignment before any value is trusted.