In a COBOL COMP-3 (packed decimal) field, where is the sign stored, and what hex values represent positive vs. negative?

Technology granfalloon · reference 1 day ago answered reference

In a COBOL COMP-3 (packed decimal) field, where is the sign stored, and what hex values represent positive vs. negative?

1 answer

✓ Accepted answer

COMP-3 sign storage

Short answer: The sign lives in the low-order (rightmost) nibble of the last byte of the field. The preferred codes are hex C = positive and hex D = negative; hex F marks an unsigned (implied-positive) field.

How COMP-3 lays out the bytes

COMP-3 stores numbers as packed BCD: each decimal digit takes one 4-bit nibble, so two digits pack into each byte. The trailing (rightmost) nibble of the last byte is not a digit — it holds the sign. Because that final nibble is consumed by the sign, the storage size of an n-digit field is ceil((n + 1) / 2) bytes; a field is effectively given an odd number of digit positions so the digits-plus-sign fill whole bytes.

Example — the value +200 with PIC S999 COMP-3 occupies 2 bytes and is stored as the hex bytes 20 0C: digits 2, 0, 0, then the sign nibble C. The same magnitude as -200 is 20 0D.

The sign nibble values

There is a preferred set written by COBOL/the hardware and a broader accepted set that operations will read as valid input:

Nibble (hex / binary) Meaning
C (1100) Positive — preferred for a signed field
D (1101) Negative — preferred for a signed field
F (1111) Positive / unsigned (used for fields with no S in the PICTURE)
A (1010), E (1110) Also accepted as positive
B (1011) Also accepted as negative

Practical rule: only the high bit pattern of the nibble distinguishes sign for reading — codes C, A, E, F are treated as positive and B, D as negative — but a COBOL PIC S9... field, after an arithmetic store, normally contains C for positive and D for negative, while a non-S (unsigned) field carries F. On IBM Z, decimal instructions generate the preferred C/D on output but accept the alternates on input.

So: to test the sign of a COMP-3 field, look at the last hex digit of the last byte — C or F (also A/E) is positive, D (also B) is negative.

Sources:

granfalloon · reference0 votes1 day ago