Definition:
BCD represents each of the digits of an unsigned decimal
as the 4-bit binary equivalents.
UNPACKED BCD:
Unpacked BCD representation contains only one decimal digit per byte.
The digit is stored in the least significant 4 bits; the most significant
4 bits are not relevant to the value of the represented number.
PACKED BCD:
Packed BCD representation packs two decimal digits into a single byte.
* * *
Example values:
Decimal------Binary---------Unpacked BCD----------Packed BCD
0-----------0000 0000---------------0000 0000-----0000 0000
1-----------0000 0001---------------0000 0001-----0000 0001
2-----------0000 0010---------------0000 0010-----0000 0010
3-----------0000 0011---------------0000 0011-----0000 0011
4-----------0000 0100---------------0000 0100-----0000 0100
5-----------0000 0101---------------0000 0101-----0000 0101
6-----------0000 0110---------------0000 0110-----0000 0110
7-----------0000 0111---------------0000 0111-----0000 0111
8-----------0000 1000---------------0000 1000-----0000 1000
9-----------0000 1001---------------0000 1001-----0000 1001
10----------0000 1010-----0000 0001 0000 0000-----0001 0000
11----------0000 1011-----0000 0001 0000 0001-----0001 0001
12----------0000 1100-----0000 0001 0000 0010-----0001 0010
13----------0000 1101-----0000 0001 0000 0011-----0001 0011
14----------0000 1110-----0000 0001 0000 0100-----0001 0100
15----------0000 1111-----0000 0001 0000 0101-----0001 0101
16----------0001 0000-----0000 0001 0000 0110-----0001 0110
17----------0001 0001-----0000 0001 0000 0111-----0001 0111
18----------0001 0010-----0000 0001 0000 1000-----0001 1000
19----------0001 0011-----0000 0001 0000 1001-----0001 1001
20----------0001 0100-----0000 0010 0000 0000-----0010 0000
==================================================
Decimal to Packed BCD:
==================================================
Example decimal 16 to Packed BCD
decVal= 16 decimal
Formula:
Packed_bcdVal = (decVal / 10) << 4 + (decVal // 10)
(decVal / 10)
00010000 / 00001010 = 00000001
Shifts the result left 4 places
00000001 << 4 = 00010000
(decVal // 10) modulus
00010000 // 10 = 00000110
(00000110 , Dec 6 is the remainder).
00010000 + 00000110 = 00010110
Result: 00010110
(00010110 represent the Packed BCD value for decimal 16)
==================================================
Packed BCD to Decimal:
==================================================
Example Packed BCD 00010110 to decimal
Packed_BCD = 00010110
Formula:
decVal = (Packed_BCD_high_nibble * 10) + Packed_BCD_low_nibble
Packed_BCD_high_nibble = 0001
Packed_BCD_low_nibble = 0110
(Packed_BCD_high_nibble * 10)
0001 * 1010 = 1010
1010 + 0110 = 00010000
Result: 00010000
(00010000 = decimal 16)
==================================================
Best regards,
Luciano
Bookmarks