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

Typecast this why?

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



Joined: 09 Mar 2010
Posts: 314
Location: Denmark

View user's profile Send private message

Typecast this why?
PostPosted: Wed Mar 16, 2011 3:30 pm     Reply with quote

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

View user's profile Send private message

PostPosted: Wed Mar 16, 2011 3:45 pm     Reply with quote

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
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