View previous topic :: View next topic |
Author |
Message |
John_Lintern
Joined: 30 Sep 2004 Posts: 14
|
Cannot multiply a 16-bit by an 8-bit to get a 32-bit ? |
Posted: Thu Sep 30, 2004 3:01 am |
|
|
I am using CCS PCW C Compiler in conjunction with MPLAB IDE to write a program for a PIC16C74B.
But I am having a problem multiplying 2 numbers together !
The result needs to be a 32-bit value and has to multiply a 16-bit value by an 8-bit value.
Take for example,
0x1234 * 0xA0 = 0x000B6080
(16bit) * (8bit) = (32bit)
But when I run the program the result gets truncated to a 16-bit value ??
So instead of getting 0x000B6080 I get 0x00006080
BUT..... if I declare ALL the variables as a 32-bit value it works !
This is ineffecient though because it uses up more memory - surely this can't be right ?
You should be able to multiply a 16-bit value by an 8-bit value to get a 32-bit value - shouldn't you ?
Below are the relevant pieces of code for my function 'Multiply':
unsigned int32 result=0x00000000; // 32-bit variable called result
unsigned int32 Multiply(unsigned int16,unsigned int8); //Multiply function
unsigned long A=0x1234; // 16-bit variable
unsigned int B=0xA0; // 8-bit variable
void(main)
{
result=Multiply(A,B);
while (TRUE)
{
}
}
// Multiply function
unsigned int32 Multiply(unsigned int16 X,unsigned int8 Y)
{
return(X * Y);
} |
|
|
kypec
Joined: 20 Sep 2003 Posts: 54
|
Use type casting |
Posted: Thu Sep 30, 2004 4:17 am |
|
|
try this inside your function:
|
|
|
Kieran
Joined: 28 Nov 2003 Posts: 39 Location: Essex UK
|
|
Posted: Thu Sep 30, 2004 5:59 am |
|
|
I would cast both first then multiply
return (int32) x * (int32) y; |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Thu Sep 30, 2004 6:18 am |
|
|
Quote: | I would cast both first then multiply
return (int32) x * (int32) y; |
That requires a 32b * 32b multiply which is what the poster did not wish. |
|
|
John_Lintern
Joined: 30 Sep 2004 Posts: 14
|
Re: Use type casting |
Posted: Thu Sep 30, 2004 7:23 am |
|
|
kypec wrote: | try this inside your function:
|
Thanks kypec !!!
That worked..... but I don't understand why ???
Why do you have to specify the return value as an int32 as you suggested ?
i.e. return (int32)X*Y
I thought the return value is specified as a 32-bit value in the lines....
unsigned int32 Multiply(unsigned int16,unsigned int8); //Multiply function
^
here
and...
unsigned int32 Multiply(unsigned int16 X,unsigned int8 Y)
^
here
So why didn't....
return (X*Y)
work then ? |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Thu Sep 30, 2004 7:28 am |
|
|
It actually casts the 'x' to a 32 bit and then multiplies it. That is why it works. (int32)(x*y) would cast the result. However, you would still get the truncated result by just casting the result. |
|
|
|