COMP-3 | COMPUTATION-3 | Packed-decimal
COMP-3 (or Packed Decimal or Packed Numeric) is a convenient way to represent decimal numbers in a compact binary-coded decimal (BCD) format, which is efficient for arithmetic operations.
Storage Size and Format -
COMP-3 stores each digit of a number in 4 bits (half byte) and uses one additional 4-bit nibble at the end to store the sign (C for positive and D for negative). For example - the decimal number +123 is stored as 123C, and -123 is stored as 123D.
COMP-3 variable contains any of the digits 0 through 9, a sign. COMP-3 can have a value not exceeding 18 decimal digits.
Efficient Use of Memory -
Digits in PICTURE clause | Storage occupied |
---|---|
1 digit | ½ Byte |
COMP-3 is efficient in terms of memory usage. For example - a COMP-3 field with a PIC S9(5) (which can store a number from -99999 to +99999) uses only 3 bytes of storage: 2.5 bytes for the digits and 0.5 bytes for the sign.
The formula for memory calculation of the COMP-3 with n digits in the declaration is -
- No. of bytes = Round ((n + 1)/2) - Where n is an odd number.
- No. of bytes = Round (n/2) - Where n is an even number.
Definition in a COBOL Program -
PICTURE clause required for COMP-3 declaration. To define a COMP-3 variable in the COBOL program, we use the USAGE IS COMP-3 clause in the DATA DIVISION. For example -
01 WS-PDN PIC 9(5) USAGE IS COMP-3.
In this example, WS-PDN is a variable that holds a five-digit decimal number in COMP-3 packed format.
Assigning Values to a COMP-3 Variable -
We can assign values to a COMP-3 variable like any other numeric variable in COBOL. For example -
MOVE 12345 TO WS-PDN.
Arithmetic Operations -
We can perform arithmetic operations (add, subtract, multiply, divide, etc.) on COMP-3 variables just like you would with any other numeric variables. For example -
ADD 100 TO WS-PDN.
Practical Example -
Scenario - Defining and initializing COMP-3 variables and using them for calculations and display.
Code -
----+----1----+----2----+----3----+----4----+----5----+
IDENTIFICATION DIVISION.
PROGRAM-ID. COMP3.
AUTHOR. MTH.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-VAR.
05 WS-WIDTH PIC S9(02) USAGE IS COMP-3.
05 WS-AREA PIC S9(06) COMP-3.
PROCEDURE DIVISION.
MOVE 10 TO WS-WIDTH.
COMPUTE WS-AREA = WS-WIDTH ** 2.
DISPLAY "LENGTH OF WS-AREA VARIABLE: "
LENGTH OF WS-AREA.
DISPLAY "AREA OF SQUARE: " WS-AREA.
STOP RUN.
Output -
LENGTH OF WS-AREA VARIABLE: 000000004 AREA OF SQUARE: 000100
Explaining Example -
WS-AREA variable is declared as COMP-3, with a signed byte plus 6 digits. A total of 7 bytes and the (n+1)/2 formula will apply as n is an odd number. So, a total of 8/2 = 4 bytes allocated for WS-AREA.