Revs on the BBC Micro

# Maths (Arithmetic): ConvertNumberToBCD

```       Name: ConvertNumberToBCD                                      [Show more]
Type: Subroutine
Category: Maths (Arithmetic)
Summary: Convert a number into binary coded decimal (BCD), for printing
Context: See this subroutine in context in the source code
References: This subroutine is called as follows:
* PrintDriverTable calls ConvertNumberToBCD
* ResetVariables calls ConvertNumberToBCD
* UpdateLapTimers calls ConvertNumberToBCD

This routine converts a number in the range 0 to 19 into a BCD number in the
range 1 to 20, so the number can be printed.

Arguments:

A                    The number to be converted into BCD (0 to 19)

Returns:

A                    The number in BCD (1 to 20)

.ConvertNumberToBCD

CMP #10                \ If A < 10, skip the following instruction as A is in
BCC ibcd1              \ the range 0 to 9, which is the same number in BCD

ADC #5                 \ A >= 10, so set A = A + 6 (as the C flag is set) to
\ convert the number into BCD, like this:
\
\   * 10 = &0A -> &10 (i.e. 10 in BCD)
\   * 11 = &0B -> &11 (i.e. 11 in BCD)
\   * 12 = &0C -> &12 (i.e. 12 in BCD)
\   * 13 = &0D -> &13 (i.e. 13 in BCD)
\   * 14 = &0E -> &14 (i.e. 14 in BCD)
\   * 15 = &0F -> &15 (i.e. 15 in BCD)
\   * 16 = &10 -> &16 (i.e. 16 in BCD)
\   * 17 = &11 -> &17 (i.e. 17 in BCD)
\   * 18 = &12 -> &18 (i.e. 18 in BCD)
\   * 19 = &13 -> &19 (i.e. 19 in BCD)

.ibcd1

SED                    \ Set the D flag to switch arithmetic to Binary Coded
\ Decimal (BCD)

ADC #1                 \ Increment A in BCD mode, so the result is in the
\ range 1 to 20

CLD                    \ Clear the D flag to switch arithmetic to normal

RTS                    \ Return from the subroutine
```