Re: Signed multiplication

From: Steve Judd <sjudd_at_ffd2.com>
Date: Sat, 14 Nov 2009 23:09:17 -0700 (MST)
Message-ID: <Pine.LNX.4.64.0911142246250.5696@chishio.swcp.com>
Uz,

There is an article in C=Hacking which covers this.  Probably the big 3D 
article (issue 16?  memory is foggy).

As I recall, the trick is recognize that a 2's complement number x has 
the value x if it's positive (high bit clear), and x-65536 if it's 
negative (high bit set).  For example, $FFFF-65536 = -1.

Thus if you were to multiply a positive number x times a negative 2's 
complement number y, you'd actually want to compute

x*(y-65536)

Therefore the algorithm goes something like:

1. multiply x*y as normal (2's complement representations)
2. if x is negative (high bit set) then subtract y from the upper 16 bits 
(subtract 65536*y)
3. if y is negative then subtract x from the upper 16 bits

Example (8-bit): 63 * -2 = $3F * $FE
multiply as normal: 63 * 254 = 16002 = $3E82
high bit of y set; subtract 63*256 = $3F00 to get $FF82 = -126 in 2's 
complement format, the correct answer.  Cool, it works.

I think that article also details how to do a fast multiply on 16-bit 
numbers (without 16-bit tables).

I believe Slang does signed multiplication this way as well.  It really 
only requires a few extra instructions on the 6502.

-Steve

On Wed, 4 Nov 2009, Ullrich von Bassewitz wrote:

>
> I'm looking for a signed 16x16 => 32 multiplication routine. Currently I'm
> using the 16x16 => 32 unsigned routine with the absolute values of the
> operands, and adjust the sign of the result if necessary. But this quite some
> overhead.
>
> Is there a fast way to do it, for example by accounting for the sign in the
> shift-and-add loop? I've tried to find a solution myself, but all I came up
> with was extending the addition to 32 bits to keep the information about
> signedness, and this is at least as slow as using absolute values and negating
> the result.
>
> Regards
>
>
>        Uz
>
>
> -- 
> Ullrich von Bassewitz                                  uz@musoftware.de
>
>       Message was sent through the cbm-hackers mailing list
>

       Message was sent through the cbm-hackers mailing list
Received on 2009-11-15 07:00:08

Archive generated by hypermail 2.2.0.