This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Long long usage question


On Sun, Mar 17, 2002 at 12:19:10AM +0100, Claus Fischer wrote:
> I need to write a function that takes four signed 32 bit values,
> builds two products, and compares the size, thusly:
> 
> int prodcomp(long a, long b, long c, long d)
> {
>     long long p1 = (long long) a * (long long) b;
>     long long p2 = (long long) c * (long long) d;
>     return p1 < p2;
> }
> 
> 
> I'm assuming that most 32 bit CPU's have an instruction for
> multiplying two 32 bit values.

Some machines have 2 flavors of 32x32->64 bit multiplies (one that assumes the
inputs are sign extended, and one that does zero extension, the x86 is an
example of this), some machines only have one flavor of 32x32->64 bit
multiplies, some have separate multiply instructions that give you the lower
and upper halves of the 64 bit result (the powerpc is an example of this), some
machines only have 32x32->32 multiplies.  A few machines, mainly for the
embedded marketplace don't have any hardware multiply support at all (though
this is rare nowadays).

Note also, some machines may have long be 64 bits.

> Questions:
> 
> 1. Does the compiler know that the cast results have their highest
>    32 bits zeroed? Does it pick a fast instruction for that case?

Ummm, the compiler does not know that the highest 32-bits are zeroed in this
case.  Because long is a signed type, the compiler does a sign extension when
converting a, b, c, and d to long long.  If you want zero extension do:

	typedef unsigned long ul;
	typedef unsigned long long ull;
	int prodcomp (ul a, ul b, ul c, ul d)
	{
	  ull p1 = (ull) a * (ull) b;
	  ull p2 = (ull) c * (ull) d;
	  return p1 < p2;
	}

-- 
Michael Meissner, Red Hat, Inc.  (GCC group)
PMB 198, 174 Littleton Road #3, Westford, Massachusetts 01886, USA
Work:	  meissner@redhat.com		phone: +1 978-486-9304
Non-work: meissner@the-meissners.org	fax:   +1 978-692-4482


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]