Re: A82: DIVsion and such..


[Prev][Next][Index][Thread]

Re: A82: DIVsion and such..



"Salix" <Salix@xpress.se> writes:
>I'm REALY new to z80 programming and as such i havent found a way to 
>do division , "real" or with a "rest".. anyone got a routine or the
>instruction ? :)

Well, division isn't so much a routine in ASM, it's an actual command.
The easiest was to divide is to, what else, use the division symbol. =)
So, want to divide 36 by 6? Code:
	
	36 / 6

Simple, eh? Course, you probably won't be dividing constants, so you
should use the general addition rules and apply them to dividing your
registers and such. Another method of dividing, which takes less clock
cycles, is shifting. SRL and SLA. These commands take the bits of the
designated register and "shift" the bits either to the left or right.
Example:

	ld A, 18
	srl A
	
Result? A = 9...let's take a closer look:

	A = 18 in decimal, in binary it's:
		10010
	We shift the bits to the right once:
		01001
	And the answer is 9 in binary. Easy. =)

Wondering what happens to the zero that was at the end of the original
value? Well, that's stored in the Carry Flag. This is very helpful to
know when making a sprite routine, btw. ;) With SRL and SLA, the "hole"
that is created from the shift is replaced with a zero. There are other
commands to replace it with a 1 or the Carry Flag, but again, they are
mostly helpful only when writing a sprite routine. =)
Another example:

		10010 = 18
	  	  10010
		/\      /\
		 ||       ||
This "hole" ______	J         L___This "excess" bit is moved to the
Carry Flag
becomes 0.

When dividing with shifting, there is a major drawback....you can only
divide by numbers to the power of 2.

	2, 4, 8, 16, 32, 64,....

(These numbers look familiar? They should. Think video games....=) ) If
you want to divide by a number other than those, you can use a
combination of shifts and add instructions (or INC) to get you where you
want to go. Remember to check your clock cycles though so you know if you
are just wasting time. Saving just *1* T-state is worth it! =) 
	
			-Scoobie


References: