Decode a packed decimal field byte by byte
Decode a COMP-3 field by splitting each byte into two nibbles, with the last nibble as the sign, in Python 3.13 on any PC.
A packed decimal field stores one digit per nibble and puts the sign in the final nibble, so a field is never read as a number until you split it. For a COBOL PIC S9(7) COMP-3 item on z/OS 3.1 the field is four bytes: seven digit nibbles and one sign nibble.
raw = bytes.fromhex("0012345C")
digits = ""
for b in raw[:-1]:
digits += f"{b >> 4}{b & 0x0F}"
digits += str(raw[-1] >> 4)
sign = raw[-1] & 0x0F
print(raw.hex().upper(), digits, f"{sign:X}")
print(int(digits))0012345C 0012345 C
12345The first three bytes give two digits each, and the high nibble of the last byte is the seventh digit. The low nibble of that last byte is the sign: X'C' means positive, so the value is +12345. The leading zeros are real digits that the field has room for, which is why the byte count is always (digits + 1) / 2 rounded up.
This works only for COMP-3. Zoned decimal and binary fields have different layouts, and a field whose last nibble is not a valid sign is damaged data, not a number.