IGNORED

# Unsigned 16 bit division

## 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).
;
; 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
```

##### 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?

##### Share on other sites

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

One of the numbers comes from a random number generator.

##### Share on other sites

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

One of the numbers comes from a random number generator.

Ah, OK, that makes sense.

## 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.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.