This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

TMS320F280041: Wrong calculation for integer multiply and divide

Part Number: TMS320F280041


Hi I have another issue about integer multiply and divide error.

CCS runtime support lib select : automatic, it shows: F021_API_F28004X_FPU32.lib

my test scenario like bellow:

unsigned int a, b, c, d;

a= 770;

b =99;

c= 47;

d = a*b*c/1000;

the correct value should be 358, but I get it is 4.

  • Unfortunately, that is not how unsigned math works in C code.

    Recall that on C28x, the type unsigned int is 16-bits wide, and the type unsigned long is 32-bits wide. 

    When an expression like a*b is seen, a type is chosen in which to perform the math.  Roughly speaking, the larger of the type of a or b is used.  In this case, they are both unsigned int, so that is what is used.  If the result of the computation cannot fit in an unsigned int, then the upper bits of the result are dropped, and the remaining bits are used as the result.  In effect, what is computed is (a * b) & 0xffff.  

    The solution is to cast at least one of the multiply operands to unsigned long.  While only one cast is needed, to be clear about what the code is doing, it is better to cast all 3 operands ...

    d = (unsigned long)a*(unsigned long)b*(unsigned long)c/1000;

    Thanks and regards,

    -George

  • Hi George,

    Thanks, 

    Best regards,

    Guangjun