Jump to content
IGNORED

Unsigned 16 bit division


GroovyBee

Recommended Posts

For my latest game I needed a modulo operation. This is the code I came up with. The speed of the function isn't critical to me because its only called a few times during screen initialisation.

 

On entry r0 should contain the divisor and r1 the dividend. The remainder is returned r2 and the quotient in r3.

 

There is no check for division by zero.

 

;------------------------------------------------------------------------------
; DivideU16ByU16
;------------------------------------------------------------------------------
; Division for 16bit unsigned integers.
;------------------------------------------------------------------------------
; In :-
; r0 - Divisor (unsigned 16bit integer).
; r1 - Dividend (unsigned 16bit integer).
; r5 - Return address.
;
; Out :-
; r2 - Remainder (unsigned 16bit integer).
; r3 - Quotient (unsigned 16bit integer).
;
; Trashes :-
; r1, r2, r3, r4
;
; Notes :-
; 1) No division by 0 check.
;------------------------------------------------------------------------------
DivideU16ByU16: PROC
   clrr r2             ; Remainder=0
   clrr r3             ; Quotient=0
   mvii #16, r4        ; Number of bits in dividend.
DivideU16ByU16Loop:
   sllc r1, 1          ; Dividend=dividend*2
   rlc r2, 1           ; Remainder=(remainder*2)+Carry
   cmpr r0, r2         ; Is remainder>=divisor?
   bnc DivideU16ByU16QuotientMultiplyOnly ; Yes... Skip subtraction.
   subr r0, r2         ; Remainder=remainder-divisor.
DivideU16ByU16QuotientMultiplyOnly:
   rlc r3, 1           ; Quotient=(quotient*2)+Carry
   decr r4             ; Repeat for all 16 bits...
   bne DivideU16ByU16Loop ; ...In the dividend
   movr r5, pc         ; All done!
   ENDP

 

Use as follows :-

 

; E.g. 7899/45
   mvii #45, r0
   mvii #7899, r1
   call DivideU16ByU16    

  • Like 1
Link to comment
Share on other sites

For my latest game I needed a modulo operation. This is the code I came up with. The speed of the function isn't critical to me because its only called a few times during screen initialisation.

 

If it's only called a few times during screen init, is there a reason you can't use the "MOD" assembler operator?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...