|
|
View previous topic :: View next topic |
Author |
Message |
Javed Shafi
Joined: 15 Mar 2004 Posts: 6
|
Typecast confusion |
Posted: Wed Sep 21, 2005 11:47 am |
|
|
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: [email protected] |
|
|
Ttelmah Guest
|
|
Posted: Wed Sep 21, 2005 2:45 pm |
|
|
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 |
|
|
|
|
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
|