8-bit Divide: Difference between revisions

From NESdev Wiki
Jump to navigationJump to search
No edit summary
No edit summary
Line 7: Line 7:
;Output with YA = (1/256)*(A/Y)
;Output with YA = (1/256)*(A/Y)
Division
Division
        sta Dvd         ;Stores divident
sta Dvd ;Stores divident
sty Dvs         ;Stores divisor
sty Dvs ;Stores divisor
lda #$00
lda #$00
sta Res         ;Clear result
sta Res ;Clear result


ldy #$10       ;The loop is for 16-bit result
ldy #$10 ;The loop is for 16-bit result
- asl Dvd
- asl Dvd
rol A ;Shift divisor in 1 bit
rol A ;Shift divisor in 1 bit
cmp Dvs         ;Check if fractional dividend is greater than divisor
cmp Dvs ;Check if fractional dividend is greater than divisor
bcc +
bcc +
sbc Dvs ;Substract (C is always set)
sbc Dvs ;Substract (C is always set)
+ rol Res         ;Shift result (1 if substation was done, 0 otherwise)
+ rol Res ;Shift result (1 if substation was done, 0 otherwise)
rol Res2
rol Res2
dey
dey

Revision as of 07:34, 25 August 2013

The following code divide two 8-bit integers (range 0...255) and outputs a 16-bit result using only real calculation, no lockup table so the size of the code is very small.

<source lang="6502">

8-bit divide
by Bregalad
Enter with A = Dividend, Y=Divisor
Output with YA = (1/256)*(A/Y)

Division sta Dvd ;Stores divident sty Dvs ;Stores divisor lda #$00 sta Res ;Clear result

ldy #$10 ;The loop is for 16-bit result - asl Dvd rol A ;Shift divisor in 1 bit cmp Dvs ;Check if fractional dividend is greater than divisor bcc + sbc Dvs ;Substract (C is always set) + rol Res ;Shift result (1 if substation was done, 0 otherwise) rol Res2 dey bne - lda Res ldy Res2 rts </source>