Integer Maths on the 6502: Multiply, Divide, BCD Scores and Printing Numbers

Atari screen showing five lines of digits: 00500, 40000, 00142, 00006 and 0100

The 6502 can add and subtract, shift and rotate, and that's all. As Mark Andrews puts it in Atari Roots, to multiply you perform a series of additions, and to divide a series of subtractions. Every Atari game that computes a screen address, scales a value or shows a score needs a few small routines for this. This guide gives tested versions of the four you need most, explains how each works, and covers the traps of the 6502's decimal mode.

What you'll learn: shift-and-add multiplication, shift-and-subtract division, converting binary to decimal digits with the decimal flag, keeping scores in BCD, printing digits into screen memory, and when tables beat all of these.

What you need: MADS and an emulator. The complete program below was assembled with MADS and run in atari800, and produced the results in the screenshot. Getting Started with 6502 Assembly covers the basics.

1. Multiplication: shift and add

Multiplying in binary is the long multiplication you learned at school, with only 0s and 1s. For each 1 bit in the multiplier, add a shifted copy of the multiplicand. Atari Roots shows two versions. The second, shorter one keeps the high byte of the result in the accumulator and shifts the whole 16-bit result right each time, instead of shifting the multiplicand left. Our routine uses that idea:

; mul8: A * X -> num (16 bits)
mul8    sta mpd             ; multiplicand
        stx mpr             ; multiplier
        lda #0
        ldx #8
m1      lsr mpr             ; next multiplier bit into carry
        bcc m2
        clc
        adc mpd             ; add multiplicand to high byte
m2      ror                 ; shift the 16-bit result right
        ror num             ; (carry from ADC goes into bit 7)
        dex
        bne m1
        sta num+1
        rts

Eight times round the loop: shift the lowest multiplier bit into the carry, and if it is 1, add the multiplicand to the high byte. Then rotate the high byte (A) and the low byte (num) right together. The carry from the addition becomes bit 7 of A, so nothing is lost. After eight bits, the 16-bit product is in A (high) and num (low). It took 250×2 to 500, and 200×200 to 40,000 ($9C40).

Multiplying by a constant is far cheaper. Each ASL doubles a value, which is how the SETCOLOR routine in Mark Chasin's Assembly Language Programming for the Atari Computers multiplies a hue by 16: four ASLs. Multiplying by 40 for a text row is ×32 + ×8: shift, save, shift twice more, add.

2. Division: shift and subtract

Division is long division in binary. Shift the dividend left into a running remainder one bit at a time. Whenever the remainder is at least the divisor, subtract and set a 1 bit in the quotient. This version divides a 16-bit value by an 8-bit one, building the quotient in the space freed by the shifted-out dividend:

; div16x8: dvd (16 bits) / A -> A=quotient, X=remainder
; quotient must fit in 8 bits (dvd+1 < divisor)
div16x8 sta divs
        ldx #8
        lda dvd+1           ; remainder starts as the high byte
d1      asl dvd             ; shift dividend left into remainder
        rol
        bcs d2              ; remainder overflowed: must subtract
        cmp divs
        bcc d3
d2      sbc divs            ; carry is set here
        inc dvd             ; set quotient bit
d3      dex
        bne d1
        tax                 ; remainder
        lda dvd             ; quotient (built in the low byte)
        rts

The BCS d2 line matters with large divisors. When the remainder's top bit shifts out into the carry, the remainder is really over 255, which is certainly bigger than the divisor, so subtract regardless. We tested both paths: 1000÷7 gave quotient 142 and remainder 6, and 65000÷254 gave 255 remainder 230. The restriction is in the comment: if the high byte of the dividend is already at least the divisor, the quotient won't fit in 8 bits.

Atari Roots gives a similar 16÷8 routine, using PHP and PLP to carry the subtraction result between iterations, and remarks that you will rarely need anything more elaborate. For bigger divisions or fractions, the floating-point ROM is there (see Using the Floating-Point ROM from Assembly Language), at a large cost in speed.

3. Decimal mode and BCD

SED puts the 6502 into decimal mode. ADC and SBC then treat each byte as two binary-coded decimal digits, one per nibble: $0099 means 99, not 153. CLD turns it off. The rules:

  • Only ADC and SBC are affected. INC, DEC, CMP and indexing work in binary as usual. So INC score does not count in decimal. Add 1 with ADC instead.
  • The carry works properly: $99 + $01 gives $00 with carry set, which is what multi-byte BCD needs.
  • On the NMOS 6502 in the Atari, the Z and N flags reflect the binary intermediate result, not the decimal answer. $99 + $01 gives $00 with N set, and $FF + $01 gives $66 with Z set. Test results with the carry or by comparing, never with BEQ or BMI straight after a decimal ADC.
  • The D flag is not cleared by interrupts on the NMOS 6502. The OS's own vertical-blank code counts with INC and DEC, which are immune, but if your VBI or DLI routine uses ADC or SBC and the main program ever runs with D set, start the interrupt routine with CLD. The status register, D flag included, is restored by RTI.

4. BCD scores

For a game score, BCD is ideal. Adding points is two decimal ADCs, and every nibble is ready to print:

; addscore: score (2-byte BCD) += A (BCD)
addscore sed
        clc
        adc score
        sta score
        lda score+1
        adc #0
        sta score+1
        cld
        rts

Pass the points as BCD too: LDA #$25 for 25 points. Our test added 1 to a score of 99 and got 0100. Keep the CLD close to the SED, so that no other code accidentally runs in decimal mode. Writing a Small Complete Game in Assembly uses exactly this pattern.

5. Binary to decimal for display

To print a binary number such as 40,000, convert it to BCD first. The decimal flag makes this a short loop: for each of the 16 bits, from the top, double the BCD total and add the bit. Doubling is just adding a value to itself, and in decimal mode the ADC does the decimal carries for you:

; bin16 -> 3-byte BCD using decimal mode
tobcd   lda #0
        sta bcd
        sta bcd+1
        sta bcd+2
        lda num
        sta t16
        lda num+1
        sta t16+1
        ldx #16
        sed                 ; decimal arithmetic on
b1      asl t16             ; top bit into carry
        rol t16+1
        lda bcd             ; bcd = bcd*2 + carry, in decimal
        adc bcd
        sta bcd
        lda bcd+1
        adc bcd+1
        sta bcd+1
        lda bcd+2
        adc bcd+2
        sta bcd+2
        dex
        bne b1
        cld                 ; ALWAYS clear decimal mode again
        rts

The bit shifted out of the binary number in ROL t16+1 is still in the carry when the first ADC runs, so it is added in at the same moment the total is doubled. Three BCD bytes hold up to 999,999, enough for any 16-bit value.

6. Printing digits into screen memory

A BCD nibble plus $10 is the internal screen code of that digit ('0' is internal code 16; see ATASCII and Keyboard Codes), so printing is a mask and an OR:

two     pha                 ; print a BCD byte as two digits
        lsr
        lsr
        lsr
        lsr
        jsr nib
        pla
nib     and #$0F
        ora #$10            ; internal code of '0'..'9'
        sta (PTR),y
        iny
        rts

PTR is a zero-page pointer to the screen row and Y the column. For ATASCII output through CIO (the E: or P: device), OR with $30 instead.

7. The complete test program

; 6502 integer maths: 8x8 multiply, 16/8 divide, binary to BCD, BCD add
SAVMSC  = $58
PTR     = $CB           ; 2 bytes, screen pointer

        org $3000

start   lda SAVMSC          ; PTR = start of screen row 1
        clc
        adc #40
        sta PTR
        lda SAVMSC+1
        adc #0
        sta PTR+1
        lda #250            ; 250 * 2
        ldx #2
        jsr mul8
        jsr showdec         ; prints 00500
        lda #200            ; 200 * 200
        ldx #200
        jsr mul8
        jsr showdec         ; prints 40000
        lda #<1000          ; 1000 / 7
        sta dvd
        lda #>1000
        sta dvd+1
        lda #7
        jsr div16x8         ; quotient in A, remainder in X
        stx tmp
        sta num
        lda #0
        sta num+1
        jsr showdec         ; prints 00142
        lda tmp
        sta num
        jsr showdec         ; prints 00006
        lda #$99            ; score $0099 + $0001 in BCD
        sta score
        lda #$00
        sta score+1
        lda #$01
        jsr addscore
        jsr showscore       ; prints 0100
loop    jmp loop

; (insert mul8, div16x8, tobcd and addscore from above here)

showdec jsr tobcd           ; print num as 5 decimal digits
        ldy #0
        lda bcd+2
        jsr nib
        lda bcd+1
        jsr two
        lda bcd
        jsr two
        jmp nextrow
showscore ldy #0
        lda score+1
        jsr two
        lda score
        jsr two
nextrow clc
        lda PTR
        adc #40
        sta PTR
        bcc nr1
        inc PTR+1
nr1     rts

; (insert two/nib from above here)

num     dta a(0)
dvd     dta a(0)
mpd     dta 0
mpr     dta 0
divs    dta 0
tmp     dta 0
t16     dta a(0)
bcd     dta 0,0,0
score   dta a(0)

        run start

Paste the routines from the earlier sections where the comments say, assemble with mads math.asm -o:math.xex, and run the result in an emulator.

8. When to use a table instead

Loops are compact but slow: each routine above runs its loop 8 or 16 times, at a few dozen cycles per pass. In time-critical code, precalculate. A 24-entry table of row addresses (low bytes and high bytes in separate tables) replaces a ×40 multiply with two indexed loads. A 256-entry table of squares gives fast multiplication via (a+b)²/4 − (a−b)²/4. Making 6502 Code Faster on this site shows how to measure which is worth it.

Troubleshooting

  • Score counts 9, A, B…: you used INC, which isn't affected by decimal mode. Use SED/CLC/ADC #1/CLD.
  • Random corruption in an interrupt routine: the main program was in decimal mode when the interrupt arrived. Add CLD at the start of the handler.
  • A branch after a decimal ADC goes the wrong way: Z and N aren't valid in decimal mode on the NMOS 6502. Use the carry.
  • Division returns nonsense: the quotient overflowed 8 bits. Check that the high byte of the dividend is less than the divisor, or use a 16÷16 routine.
  • Digits show as punctuation: you added $30 (ATASCII) when writing to screen memory. Use $10.

Further reading

  • Mark Andrews, Atari Roots: A Guide to Atari Assembly Language (Datamost): multiplication, long division and BCD.
  • Mark Chasin, Assembly Language Programming for the Atari Computers (1984).
  • Avery Lee, Altirra Hardware Reference Manual, section 3.2 "Decimal mode".
  • On this site: Writing a Small Complete Game in Assembly, Using the Floating-Point ROM from Assembly Language, Making 6502 Code Faster.

Credits