"perry.yuan" <perry.yuan@gmail.comwrites:
Quote:
I am looking for C code for multiplying 32bit by 32bit operands and
getting a 64bit product. i.e.
>
U32 m1, m2;
U64 p = m1 * m2;
>
Of course I can use
>
U64 p = (U64) m1 * m2;
>
But, disassembly listing shows that generated code calls a 64bit x
64bit multiplication routine.
>
The target I am working on has a 32bit x 32 bit =64bit machine
instruction but doesn't have any 64bit x 64 bit instruction. Before I
wet my hand on assembly programming, I love to see any C code solution
to it.
There is no direct way in C to specify a 32 x 32 =64 multiplication.
(For that matter, there's no guarantee that a given implementation has
32-bit and 64-bit types, but most do, apparently including yours.)
Assuming U32 and U64 are 32-bit and 64-bit unsigned integer types,
then this:
U64 p = (U64)m1 * m2;
specifies the following operations in the C abstract machine:
Convert the 32-bit value of m1 to 64 bits (because of the cast).
Convert the 32-bit value of m2 to 64 bits (promoted by "*").
Multiply the two 64-bit values, yielding a 64-bit result.
Initialize p, a 64-bit object, with that result.
If the compiler is clever enough to figure out that it can use the
32x32->64 multiplication instruction instead, it's free to perform
that optimization, as long as it can guarantee that it will yield the
same result in all possible cases (which I believe is the case here).
Take a look at your compiler's documentation, and try telling it to
generate optimized code. You might need to use some option to tell it
to generate code for a particular flavor of whatever CPU you're using.
There's no guarantee that this will work (as long as the generated
code gets the right answer, the standard doesn't care how it got it).
If that fails, you might consider writing a small assembly routine and
calling it from your C code, or perhaps using inline assembly. Both
methods are non-standard; if you have any questions, you'll need to
ask in a compiler-specific or platform-specific newsgroup. You'll
also be giving up some portability, which may or may not be a problem
for you.
--
Keith Thompson (The_Other_Keith)
kst-u@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"