hmmpic
Joined: 09 Mar 2010 Posts: 314 Location: Denmark
|
Typecast this why? |
Posted: Wed Mar 16, 2011 3:30 pm |
|
|
Dont understand this, why is typecasting needed here?
Code: | signed int8 res;
int8 ad;
1) if without casting wrong result.
res=(ad-125)/2.50;
2) if type cast is placed there, it work.
res=((signed int)ad-125)/2.50;
3) if type cast is placed there, wrong result.
res=(signed int)(ad-125)/2.50; |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19509
|
|
Posted: Wed Mar 16, 2011 3:45 pm |
|
|
Because an int, in CCS, is unsigned by default (in the manual). If the ADC value is below 125, the arithmetic in the first case will give an overflowed result.
Two(+) parts to this. In C, the standard is that for each arithmetic section (so the ad-125 to begin with), the 'type' of the highest component is used. The 'order', is in the C reference manual. In this case, both parts are int8, so int8 (unsigned) arithmetic will be used.
res=(ad+(-125))/2.50;
will work, since the constant number, is now '-ve', and hence signed, and would probably be a fraction faster.
Second part though is that on most C's, the default integer is signed, so for this particular case, casting would not be needed.
Third (+) part, is that on C's on the PC for example, the code will normally use int16 as the 'lowest' type, and the hardware performs the arithmetic, and automatically returns the -ve sign.
Best Wishes |
|