View previous topic :: View next topic |
Author |
Message |
tripper269
Joined: 06 May 2013 Posts: 33 Location: Toronto
|
int8 subtraction problem |
Posted: Thu Feb 08, 2018 4:10 pm |
|
|
Hi there,
I am trying to subtract two int8 numbers and store result in signed int16 or float variable. But when the difference between these is more than 127, result look like under flowed. I tried all kind of casting but didn't work. below is the complete code.
#include <33FJ256GP710A.h>
#fuses XT,NOWDT,NOPROTECT
#use delay(crystal = 8Mhz)
int8 SP = 0, MV = 130, x,y,z;
signed int16 Error;
void main()
{
Error = SP - MV;
x = 2;
y = 3;
z = x * y;
while(1)
{
}
}
I really appreciate if someone can help. |
|
|
tripper269
Joined: 06 May 2013 Posts: 33 Location: Toronto
|
|
Posted: Thu Feb 08, 2018 4:18 pm |
|
|
I think this will work
(int8)Error = SP - MV; |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Thu Feb 08, 2018 7:12 pm |
|
|
1. How are you testing this ? In MPLAB simulator ? If so, what version of
MPLAB are you using ? Or in hardware ?
2. How are you displaying the result ? In a watch window, or in a printf
statement that is not shown ?
The details of these things can make a difference in explaining why
you had to cast it to int8. |
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9246 Location: Greensville,Ontario
|
|
Posted: Thu Feb 08, 2018 7:57 pm |
|
|
I'm wondering what the compiler default for int8 is for the 33 series PICs is ? It might be unsigned and that could be a problem.....though I don't use the 33s so don't know, just an idea.
PCMP is onto another posibility as your 'complete code' doesn't display the result, so I have to assume some other means and that (simulator, debug, ??) could easily be the culprit.
If you post several data and the results, that might show a pattern as to what is happening.
Jay |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19552
|
|
Posted: Fri Feb 09, 2018 1:00 am |
|
|
The problem is here:
MV = 130
On the PIC24/30/33, the default for _all_ integers, is 'signed'.
The signed int8 can't hold '130'.
Now the pre-processor, just like all of C, will not warn you if a value won't fit.
However I do have to ask, 'why do this'?. The default integer size on these PIC's is a signed int16. These are handled as efficiently (in fact in many cases _more_ efficiently), as an int8. Just declare the values as 'int', and it'll all work.....
byte by default is an unsigned int8. |
|
|
|