SX Microcontroller Math Method

Divide 16 bit int by 16 bit int to 16 bit int with 16 bit int remander

by Nikolai Golovchenko

; uint16 x = uint16 x / uint16 y
;
; Input:
;  x, x+1 - 16 bit unsigned integer dividend (x - lsb, x+1 - msb)
;  y, y+1 - 16 bit unsigned integer divisor
; Output:
;  x, x+1 - 16 bit unsigned integer quotient
; Temporary:
;  counter
;  x+2, x+3 - 16 bit remainder
;  temp - remainder extension
; Size: 36 instructions
; Max timing: 6+16*(5+14+4)-2+2+3=377 cycles


div16by16
	clr	x+2	;clear
	clr	x+3	;remainder
div16by16loopinit
	clr	temp	;clear remainder extension
	mov	W, #16
	mov	counter, W
	stc		;first iteration will be subtraction
div16by16loop
        ;shift in next result bit and shift out next
        ;dividend bit to remainder

	rl	x	;shift lsb
	rl	x+1	;shift msb
	rl	x+2
	rl	x+3
	rl	temp

	mov	W, y
	sb	x.0
	jmp	div16by16add

        ;subtract divisor from remainder
	sub	x+2, W
	mov	W, y+1
	sc
	movsz	W, ++y+1
	sub	x+3, W
	mov	W, #1
	sc
	sub	temp, W
	jmp	div16by16next

div16by16add
        ;add divisor to remainder
	add	x+2, W
	mov	W, y+1
	snc
	movsz	W, ++y+1
	add	x+3, W
	mov	W, #1
	snc
	add	temp, W

div16by16next
        ;carry is next result bit
	decsz	counter
	jmp	div16by16loop

;shift in last bit
	rl	x
	rl	x+1
	ret

See also: