AnsweredAssumed Answered

compiler math - or type cast 32 bit math to 16 bit constant.

Question asked by Rick Shaich on May 30, 2007
Latest reply on May 31, 2007 by Rick Shaich
I am looking for the best way to do math at the compiler level in 32 bit (unsigned long) using unsigned short #defines and assign to unsigned short constants.  I have lots of formulas that define constants that are based on values that we keep changing as the clients needs change.  I don't want to have to keep changing my code so I want formulas in the constant declarations.

The issue seems to be that if the formula, in any step exceeds the variable definition it craps out.
I guess I should think that the compiler could say do the calcs in floating point and then assign the int result to a 16 bit constant.
Or at least do it in 32bit int and assign the result to a 16 bit unsigned int constant. So for example I have this.

#define PWM_MODULUS 0x0400
#define V_PULLIN  100
#define V_HOLDING 18
const unsigned short PWM_HOLDING  =     (PWM_MODULUS *  V_HOLDING / 120)
const unsigned short PWM_PULLIN = ((PWM_MODULUS *  V_PULLIN) / 120)

PWM_HOLDING works fine and gets assigned 153. The 0.6 is lost. (I know I should do ( (PWM_MODULUS *  V_HOLDING / 125) +1) so it rounds correctly)
However even though PWM_PULLIN  should be 853, a legal value for an unsigned short, it does not work since PWM_MODULUS *  V_PULLIN is > 0xFFFF.   It seems this should work since the compiler should be able to handle the math, but it does not.  Since I keep changing V_Pullin, V_Holding, and PWM_Modulus it would be nice to get this working. How should this be done?

I assume I could make my #defines 32 bit (how do I do that can I say #define V_PULLIN  100L) but in other places in the code I need them to be just byte (char) size so I want to leave it alone.
So the question is how can I tell the compiler that for constants I want to have mixed types do the math at long (32 bit) and then save the result to a short (16 bit) constant?

Is there a compiler directive or way to state to do the math as unsigned long and assign the result as unsigned short?

Also I need to do lots of 24 bit math. I know long is 32 bit, short is 16 bit but is there a definition for a 24 bit word? I don't have that much memory so a 3 byte word would be nice over a 4 byte.

Oh this is with CW 5.1 on a 9S08AW part if that matters.

Message Edited by RShaich on 2007-05-30 06:01 PM