Thread: Math Gone Wrong
View Single Post
  #8   Spotlight this post!  
Unread 23-01-2005, 10:20
BradAMiller BradAMiller is offline
Registered User
AKA: Brad
#0190 ( Gompei and the Herd)
Team Role: Mentor
 
Join Date: Mar 2004
Location: Worcester, MA
Posts: 592
BradAMiller has a brilliant futureBradAMiller has a brilliant futureBradAMiller has a brilliant futureBradAMiller has a brilliant futureBradAMiller has a brilliant futureBradAMiller has a brilliant futureBradAMiller has a brilliant futureBradAMiller has a brilliant futureBradAMiller has a brilliant futureBradAMiller has a brilliant futureBradAMiller has a brilliant future
Re: Math Gone Wrong

Just to clarify further (and we had this problem too):

The C standards says that integer arithmetic will be automatically promoted to integer size, that is 16 bits. So for signed integers the range is -32768 to 32767 and for unsigned the range is 0 to 65536.

The Microchip compiler has a "feature" that will try to optimize the size and speed of the program by keeping expressions at the smallest size possible. What you're seeing is a result of this quirk in the compiler.

If you multiply two values together (even constants!) where the values can be represented as characters, then the math is done with byte arithmetic. So writing this expression:

8* 25

Gives you an answer of -56 because both 8 and 25 can fit in chars and so the math is done with chars (instead of the usual standard promotion to ints), the answer overflows the char range, and you get -56.

In your case you were multiplying 2*p1_x. 2 can fit in a char, p1_x is a char, so the math is carried out as bytes. Any time 2*p1_x was greater than a byte you had overflow and the wrong answer.