Binary conversion to BCD usually uses the division operation to find Bits, 10, hundred, and other positions on the number, but because of the division of the module occupies too much resources, and when the number of binary digits, the use of assembly language in the 8-bit 51 single-chip microcomputer is difficult to achieve, so commonly used plus three shift method of arbitrary bits of the binary number into the BCD code.
An example of the addition of a three-shift method (excerpt from http://www.360doc.com/content/11/0223/17/5169677_95465965.shtml):
The principle of adding a three-shift method:
1. Four-bit binary is greater than 15 carry (1111b->10000b), four-bit BCD is greater than 9 carry (1001->10000), shut up four-bit binary number is greater than 9 o'clock rounding, that is, 1111b->10101, just 15 of the BCD code, That is, the four-bit binary every 9 plus 6, is equal to its BCD code.
2. How does the 5-bit binary convert it? Take 11110B (30D) For example, 11110B from 1111B left one is multiply two get, will 15 BCD code 10101 also left one bit, 00101010, new low four-bit value 1010 by the old low four-bit value 0101 times two, high four-bit the same, Since the low four-bit 1010 is greater than 9, the rounding is 00110000 just 30.
3. As seen from the previous step, as long as the left shift and every 9 into 1, you can convert any bit 2 binary number is the BCD code.
4. But the algorithm adds three shifts instead of a shift plus six. Because the former occupies less resources than the latter, but in the algorithm is equivalent, the former judge whether the number is greater than or equal to 5, if greater than or equal to 5 plus 3, then shift, that is (5+3) * = 16 (1), the latter is the first shift after the judgment is greater than or equal to 10, and 10 (6).
5. Add 3 after the shift algorithm has a point to note that the last four bits of time without the need to determine whether the greater than or equal to 5, because there is no shift in the steps, can not implement the equivalent principle described in step 4.