View previous topic :: View next topic |
Author |
Message |
sergiofil
Joined: 27 Oct 2011 Posts: 3 Location: Portugal
|
Math operation problem |
Posted: Sat Oct 13, 2012 6:45 pm |
|
|
Hi,
I'm programming a PIC18f4580 with PCH compiler and i was getting an unexpected performance by the pic. So, after debugging the code, I found the problem. It is the following math operation:
vars:
Code: |
temp: unsigned int16;
a: BYTE , value is 81
myList.offset; unsigned int8; value is 32
myList.x; unsigned int8; value is 8
myList.y; unsigned int8; value is 12
(...)
temp=((a-myList.offset)*((myList.x/8)*myList.y))+4;
|
I think that the result should be:
Code: |
temp = ((81-32)*((8/8)*12))+4
temp = (49*12)+4
temp = 592
|
But the pic result is: temp = 80 !!!!!
So, I would like to understand what is wrong, to don't repeat the mistake the next time!!
Best Regards,
Sérgio Silva |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Sat Oct 13, 2012 9:06 pm |
|
|
If you want the compiler to do int16 multiplication, you need to cast one
of the operands to an int16, as shown below in bold:
Quote: | temp=((int16)(a-myList.offset)*((myList.x/8)*myList.y))+4; |
Then you will get 592. In other words, it doesn't do automatic type
promotion. You need to tell it what to do.
Another option is to use the _mul() function. It will return a 16-bit
result for two 8-bit operands. See the CCS manual:
http://www.ccsinfo.com/downloads/ccs_c_manual.pdf |
|
|
sergiofil
Joined: 27 Oct 2011 Posts: 3 Location: Portugal
|
|
Posted: Sun Oct 14, 2012 5:15 am |
|
|
Thanks for the explanation!
I have seen the _mul() function in manual, but i never tried to use it!
Best Regards,
Sérgio Silva |
|
|
|