Divide by 3: Difference between revisions

From NESdev Wiki
Jump to navigationJump to search
No edit summary
(see also)
 
(One intermediate revision by one other user not shown)
Line 5: Line 5:
== 16-bit dividend, no remainder ==
== 16-bit dividend, no remainder ==


<source lang="6502">
<pre>
  ; divide 16 bit number by 3 by multiplying by 1/3
  ; divide 16 bit number by 3 by multiplying by 1/3
  ; enter with
  ; enter with
Line 48: Line 48:
  rts
  rts
.endproc
.endproc
</source>
</pre>


== 8-bit dividend, no remainder ==
== 8-bit dividend, no remainder ==


<source lang="6502">
<pre>
  ; enter with number to be divided in A
  ; enter with number to be divided in A
  ; answer returned in A
  ; answer returned in A
Line 73: Line 73:
  rts
  rts
.endproc
.endproc
</source>
</pre>


==References==
==References==
*[http://forums.nesdev.org/viewtopic.php?p=74242#p74242 bogax's post]
*[http://forums.nesdev.org/viewtopic.php?p=74242#p74242 bogax's post]
==See also==
*[[Division by a constant integer#Division by a constant]]

Latest revision as of 14:08, 31 March 2023

A lot of times, you need to divide something by 3. One way is to multiply by $55.

16-bit dividend, no remainder

 ; divide 16 bit number by 3 by multiplying by 1/3
 ; enter with
 ; A containing the hi byte of the number to be divided by 3
 ; Y containing the lo byte of the number to be divided by 3
 ; the hi byte of the partial product is kept in A or saved
 ; on the stack when neccessary
 ; the product (N/3 quotient) is returned hi byte in A,
 ; lo byte in Y

.proc div3_ay

 ; save the number in lo_temp, hi_temp

 sty lo_temp
 sty lo_product
 sta hi_temp

 ldy #$09
 clc
 bcc ENTER

 ; each pass through loop adds the number in
 ; lo_temp, hi_temp to the partial product and
 ; then divides the partial product by 4

LOOP:
 pha
 lda lo_product
 adc lo_temp
 sta lo_product
 pla
 adc hi_temp
ENTER:
 ror
 ror lo_product
 lsr
 ror lo_product
 dey
 bne LOOP
 ldy lo_product
 rts
.endproc

8-bit dividend, no remainder

 ; enter with number to be divided in A
 ; answer returned in A
.proc div3_a
 sta temp
 lsr
 lsr
 adc temp
 ror
 lsr
 adc temp
 ror
 lsr
 adc temp
 ror
 lsr
 adc temp
 ror
 lsr
 rts
.endproc

References

See also