From Newsgroup: comp.sys.cbm
On Tue, 15 Jul 2003 23:27:44 GMT,
fjb@pathcom.com (Jim Butterfield)
wrote:
(... details not included; if interested, ask).
In response to an email followup from David Mueller. Note that this
is somewhat cryptic; my posting service doesn't seem to be able to
cope with longer uploads. (Why? why?)
How can I divide a Number by ten?
Subtract ten repeatedly until the result is less than ten,
while counting the subtractions. For a 16-bit number,
subtract 10,000 repeatedly, then subtract 1000 repeatedly;
each time, you'll get a decimal digit. That's generally how
it's done in the kernal, but a general division algorithm may
be better.
I seem to remember that
dividing by two is done by just rotating ...
But I really can't remember how to do this with any number besides 2.
You're right about "two"; other numbers take a little more
coding. Here's how a general division algorithm works: Take
the number to be divided, and tack a zero byte at the high-order
end. Now shift the whole mess one bit to the left. Check the
(previously zero) byte at the top, to see if it's higher that
your divisor (ten in this case). If it is, subtract the
divisor and set the low bit in the quotient. Repeat this
shifting left, testing, subtracting if necessary, for as many
times as you have bits in the original number; be sure to
shift the quotient left each time, too. The remainder will be
in the high (originally zero) bit.
Try working this out on paper first; an elegant trick is to
put the quotient into the space the original number occupied;
thus, as the number moves out, the quotient moves in and the
single left-shift sequence does both.
And what is this algorithm, using the "decimal" mode?
Simpler, and quite astonishing. Set up a decimal (BCD) zero
result area. Now, for each bit of the argument:
-shift the whole argument one bit left; don't touch the
resulting carry bit;
-in Decimal mode, add the BCD result area to itself. You'll
be doubling the number (in BCD mode); and if the carry bit was
set, you'll also add one.
When you've done this for all the bits of the argument, the
BCD area will contain the decimal value. You'll have to split
apart the two digits in each byte, of course, for printing.
--Jim
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 80,000 Newsgroups - 16 Different Servers! =-----
--- Synchronet 3.18b-Win32 NewsLink 1.113