8-bit Divide: Difference between revisions
From NESdev Wiki
Jump to navigationJump to search
m (clean up format) |
(when the rol instruction itself produces a carry, subtract immediately; ring counter to save 15 deys; remainder) |
||
Line 5: | Line 5: | ||
;by Bregalad | ;by Bregalad | ||
;Enter with A = Dividend, Y=Divisor | ;Enter with A = Dividend, Y=Divisor | ||
;Output with | ;Output with YX = (A/Y) << 8, A = remainder | ||
Division | Division | ||
sta Dvd ;Stores dividend | sta Dvd ;Stores dividend | ||
sty Dvs ;Stores divisor | sty Dvs ;Stores divisor | ||
ldy #$00 | |||
sty ResHi ;Clear result, setting up a ring counter | |||
iny ;by initializing the result to $0001. | |||
sty Res ;When the 1 gets shifted out, we're done | |||
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 | ||
bcs + ;If carry is set, the dividend is already greater | |||
cmp Dvs ;Check if fractional dividend is greater than divisor | cmp Dvs ;Check if fractional dividend is greater than divisor | ||
bcc + | bcc ++ | ||
+ sbc Dvs ;Subtract (C is always set) | |||
+ rol Res ;Shift result (1 if subtraction was done, 0 otherwise) | ++ rol Res ;Shift result (1 if subtraction was done, 0 otherwise) | ||
rol | rol ResHi | ||
bcc - | |||
ldx Res | |||
ldy ResHi | |||
ldy | |||
rts | rts | ||
</pre> | </pre> | ||
[[Category:Arithmetic]] | [[Category:Arithmetic]] |
Revision as of 23:04, 9 October 2014
The following code divide two 8-bit integers (range 0...255) and outputs a 16-bit result in fixed point 8.8 format. It is only using real calculations, no lookup table, thus the size of the code is very small.
;8-bit divide ;by Bregalad ;Enter with A = Dividend, Y=Divisor ;Output with YX = (A/Y) << 8, A = remainder Division sta Dvd ;Stores dividend sty Dvs ;Stores divisor ldy #$00 sty ResHi ;Clear result, setting up a ring counter iny ;by initializing the result to $0001. sty Res ;When the 1 gets shifted out, we're done ldy #$10 ;The loop is for 16-bit result - asl Dvd rol A ;Shift divisor in 1 bit bcs + ;If carry is set, the dividend is already greater cmp Dvs ;Check if fractional dividend is greater than divisor bcc ++ + sbc Dvs ;Subtract (C is always set) ++ rol Res ;Shift result (1 if subtraction was done, 0 otherwise) rol ResHi bcc - ldx Res ldy ResHi rts