Saturday, July 30, 2016

Zoned Decimal and packed Decimal (COMP- 3) fields. How Does COMP 3 saves storage spaces?

Two computer codes which are used  for internal representation of data are EBCDIC and ASCII.
Extended Binary coded decimal interchange(EBCDIC)  code is a 8 bit character encoding standard used in IBM environment.
Most of the other Non IBM machines use ASCII standard.
Below is the EBCDIC representation of the alphabets and numbers followed in IBM environment.
EBCDIC represenation of Aphabets and Numerals

 All characters & numbers are represented in 8 bits. These 8 bits can be  broken into two 4 bit segments. For historical reasons, the  high order 4 bits are called zone part and low order 4 bits are called digits part.
Each of these 4 bits are represented by one hexadecimal character. Thus each 8 bit EBCDIC can be represented by  two character hexadecimal value. The high order 4 bits are used to represent whether the value stored is a letter,positive or negative number. Low order 4 bits represents numbers 0-9.
Let us see how the letter D is stored internally.(Map with the chart above)

In similar fashion, we can see how the letter 8 will be stored in the system( Map with the chart above)

Thus we see that in zoned decimal each byte represents one digit.

So, how will the positive number 62587 be stored in the system?
Zoned decimal number in EBCDIC repreentaion
In  zoned decimal, the zone portion of the rightmost byte represents the sign of the number.
For positive number, the zone portion is always 1111.
For negative number the zone portion becomes  1101.
Thus -6 can will be represented  as: 1101(Zone part) 0110(Digit part)

Packed Decimal fields: How does it save spaces?  Let's see how it works.

In  packed decimal format, the zone portion is stripped from each byte, so that two digits can be packed together in one byte.This way the space for zone portion of each byte can be used to represent another digit. Thus two digits are represented in single byte there by saving the space.
Only the zone portion of the low order or the rightmost byte is kept for storing the sign of the field.
Considering the same example, see how the number 62587 will be stored in packed decimal format.
Space utilized will be reduced from 5 bytes to 3 bytes.

Number :                                6               2              5             8                7
Packed decimal representation
We can see that two digits are packed in single byte by stripping of the zone portion of all the bytes except the last byte (marked in brown).
Had it been a negative number the last byte would have contained 1101 in place of 1111.

This way, a packed decimal number saves space by packing two digits in one byte.