home
table of contents
Programming
July 2002
email

Divide by 100 without using a divide instruction

The Challenge:
Is there any clever way to divide an 16 bit number by 100 on assembly without using the divide operation?

Reply:
The following code should work:

#	R1 contains the number x to be divided by 100
#	R1 and R2 are registers; 'mov' is a copy from one
#	register to another; 'shr' and 'shl' are shift right
#	and shift left instructions.
	mov r1, r2	# copy x into r2
	shl r2, 5	# r2 has x/32
	add r1, r2	# r2 has x*(33/32)
	shr r2, 2	# r2 has x*(33/8)
	add r2, r1	# r1 has x*(41/8)
	shl r1, 9	# r1 has x*(41/4096)
#
#	This may be already good enough, but for full 16 bit
#	accuracy use the additional three instructions to
#	multiply the contents of r1 by 1023/1024
#
	mov r1, r2	# r2 has x*(41/4096)
	shl r2, 10	# r2 has x*(41/4194304)
	sub r2, r1	# r1 has x*(41943/4194304)
#
#	If we are doing 32 bit registers and 32 bit accuracy
#	include the following three instructions to multiply
#	the contents of r1 by 1048577/1048576
#
	mov r1, r2	# r2 has x*(41943/4194304)
	shl r2, 20	# r2 has x*(41943/4398046511104)
	add r2, r1	# r1 has x*(43980465111/4398046511104)


This page was last updated July 1, 2002.

home
table of contents
Programming
July 2002
email