Hi,
I have a customer asking why our compiler truncates the results (product) to 16-bits when multiplying two 16-bit values, even when the product has been defined as a 32-bit value. This is a general question, but for your reference, I'm using a MSP430F6779A and CCS v6.2.0.
#include <msp430.h> #include <stdint.h> unsigned int int_operand1 = 0; // 16-bit unsigned int int_operand2 = 0; // 16-bit unsigned long long_operand = 0; // 32-bit unsigned int int_product = 0; // 16-bit unsigned long long_product1 = 0; // 32-bit unsigned long long_product2 = 0; // 32-bit void main(void) { WDTCTL = WDTPW | WDTHOLD; // Stop WDT int_operand1 = 9; // 0x9 int_operand2 = 10000; // 0x2710 long_operand = 10000; // 0x00002710 long_product1 = int_operand1 * int_operand2; // 32-bit (truncates to 16-bit result) = 16-bit x 16-bit long_product2 = int_operand1 * long_operand; // 32-bit (32-bit result) = 16-bit x 32-bit while(1){ __no_operation(); // For debugger } }
From what I've found, the result (product) will be the same size as the larger operand of the two operands when multiplying two values in C. If both operands are 16-bit, I would expect that the result would be 16-bit. This seems to be a C limitation, but it makes sense.
For a workaround, I recommended that the customer declare one of the operands as 32-bit to ensure the result (product) always equals a 32-bit value without any truncation. However, they do not want to type cast all their variables and are suggesting that our compiler should take care of this automatically. Can you please confirm if this is an issue with our compiler or just correct implementation of the C standard? I tried the code above in IAR, and the results were the same.
Here are some references that I found relating to this topic:
- http://www.ti.com/lit/an/spra683/spra683.pdf
- https://e2e.ti.com/support/microcontrollers/c2000/f/171/t/32981
- https://e2e.ti.com/support/microcontrollers/msp430/f/166/t/159764
- http://processors.wiki.ti.com/index.php/MCU_Compiler_v15#Improved_code_generation_of_32x32.3D.3E64_multiplies_.28C2000.2C_MSP430.29
Thank you.
Regards,
James
MSP Customer Applications