CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to CCS Technical Support

Math operation problem

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
sergiofil



Joined: 27 Oct 2011
Posts: 3
Location: Portugal

View user's profile Send private message

Math operation problem
PostPosted: Sat Oct 13, 2012 6:45 pm     Reply with quote

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

View user's profile Send private message

PostPosted: Sat Oct 13, 2012 9:06 pm     Reply with quote

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

View user's profile Send private message

PostPosted: Sun Oct 14, 2012 5:15 am     Reply with quote

Thanks for the explanation!

I have seen the _mul() function in manual, but i never tried to use it!


Best Regards,
Sérgio Silva
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group