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 confusion

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



Joined: 15 Mar 2004
Posts: 6

View user's profile Send private message Send e-mail

Typecast confusion
PostPosted: Wed Sep 21, 2005 11:47 am     Reply with quote

CODE:

unsigned int32 iTargetSeconds; // target delay in seconds
int16 iWeighting[4] = { 60000, 6000, 600, 60};
int8 iReadCommand[5]
.
.
.
// Convert delay from str of 4 chars to long int
for ( iCount=0 ; iCount < 4 ; iCount++)
{
iTargetSeconds = iTargetSeconds +
(iReadCommand[ iCount+1 ] * iWeighting[ iCount ]);

}

I had a problem with the above code say iReadCommand[] = "25820" what would the calculated value be for iTargetSeconds? (It should be
5820 * 60)

I know there is a problem with a signed int16 holiding 60000, I should change this to unsigned int32.

The other question is typecasting iReadCommand returns an int8 should this be typecast to (unsigned int32) before I multiply by an unsigned int 32
or will the compiler use the larger of the 2 variables to calculate the result
_________________
Javed Shafi

email: JShafi@aberdeen.oilfield.slb.com
Ttelmah
Guest







PostPosted: Wed Sep 21, 2005 2:45 pm     Reply with quote

First, how can 'ireadCommand' equal 25820?. You have this variable declared as an int8.
Next, propogate types to the higher type, _before_ performing arithmetic, if that arithmetic is likely to overflow the original type. so if you have two int16 values, one holding 5820, and the other 60, this sum will not fit in an int16, so force the conversion in advance. So:

int16 a,b;
int32 c;

a=5820;
b=60;

c=a*b;

Will give the wrong answer, since the sum cannot be performed in an int16 type. Instead use:

c=(int32)a*b;

Which forces the variable a, to be extended to 32bits, and the sum to therefore be done in 32bit arithmetic.

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