Skip to content
systemcoding.dev
Mainframe

Read a zoned decimal sign from the last byte

In zoned decimal each byte is a digit with a zone nibble in front, and the zone of the last byte carries the sign, shown here in Python 3.13.

1 min read
Summarize in AI

A zoned decimal field (COBOL PIC S9(3) DISPLAY) holds one digit per byte, and unlike packed decimal the sign hides in the zone nibble of the last byte only. Every earlier byte has the zone X'F'; the last byte has X'C' for positive, X'D' for negative, or X'F' when the field is unsigned.

zoned.pypython
def zoned(raw):
    digits = "".join(str(b & 0x0F) for b in raw)
    zone = raw[-1] >> 4
    return int(digits) * (-1 if zone in (0xB, 0xD) else 1)

print(zoned(bytes.fromhex("F1F2C3")))
print(zoned(bytes.fromhex("F1F2D3")))
Text
123
-123

Both fields have the digits 1, 2 and 3, because the low nibble of every byte is the digit. Only the high nibble of the final byte differs: X'C3' is +3 and X'D3' is -3. That is why a negative amount in a dump ends in a byte like D3, which in EBCDIC code page 037 prints as the letter L.

If the file was converted to ASCII before you read it, the sign nibble is gone and you must handle overpunch characters instead. This snippet reads raw EBCDIC bytes only.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.