Menu
CoddyTech

COMP and COMP-3

Part of the Data and Numbers section of Coddy's COBOL Programming journey. Lesson 18 of 23.

So far every number was stored as text, one byte per digit. That is USAGE DISPLAY, the default.

COMP-3, or packed decimal, stores two digits per byte, with the sign in the last half byte. PIC S9(7)V99 COMP-3 takes 5 bytes instead of 9. Mainframe files keep amounts of money this way.

01 BALANCE PIC S9(7)V99 COMP-3.

COMP, also written BINARY, stores a binary whole number: 2 bytes for up to 4 digits, 4 bytes for up to 9. Counters often use it.

01 REC-COUNT PIC 9(4) COMP.

The picture still sets the digits and decimals, and MOVE, ADD and COMPUTE work the same. Only the bytes differ. To print one, move it into an edited field.

LENGTH OF gives a field's size in bytes: DISPLAY LENGTH OF BALANCE prints 5.

challenge icon

Challenge

Easy

BALANCE takes 9 bytes, one per digit. Declare it as packed decimal instead, so the program prints Bytes: 5. The balance it prints stays the same.

Try it yourself

       IDENTIFICATION DIVISION.
       PROGRAM-ID. PACKED.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 BALANCE PIC S9(7)V99 VALUE 1250.75.
       01 BAL-OUT PIC ZZZ9.99.
       PROCEDURE DIVISION.
           SUBTRACT 300 FROM BALANCE.
           DISPLAY "Bytes: " LENGTH OF BALANCE.
           MOVE BALANCE TO BAL-OUT.
           DISPLAY "Balance: " BAL-OUT.
           STOP RUN.

All lessons in Data and Numbers