8-bit Divide: Difference between revisions

From NESdev Wiki
Jump to navigationJump to search
m (spell check)
(Output format is fixed point 8.8 (otherwise this makes few sense))
Line 1: Line 1:
The following code divide two 8-bit integers (range 0...255) and outputs a 16-bit result using only real calculation, no lookup table so the size of the code is very small.
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.


<pre>
<pre>

Revision as of 21:14, 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 YA = (1/256)*(A/Y)
Division
	sta Dvd		;Stores dividend
	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 	;Subtract (C is always set)
+	rol Res		;Shift result (1 if subtraction was done, 0 otherwise)
	rol Res2
	dey
	bne -
	lda Res
	ldy Res2
	rts