Home > Blockchain >  Integer conversion resulted in truncation
Integer conversion resulted in truncation

Time:03-29

In embedded C, I just input a value of 500000 into a 16-bit slot. It's giving me the warning of "Integer conversion resulted in truncation". In this event, does that mean the value is set to 65535, 41248 (which is the remainder of 500000/65536), or another value? Or is there not enough information given here to determine it's value and there are other factors at play? Please let me know if more info is needed.

(Sample code, in case it helps)

TA0CCR0 = 500000-1;                     
                                        
TA0CCTL1 = OUTMOD_7;                    
                                        
TA0CCR1 = 250000;                          
                                    
TA0CCTL2 = OUTMOD_7;   
             
TA0CCR2 = 850;   
                   
TA0CTL = TASSEL__SMCLK | MC__UP | TACLR;

CodePudding user response:

It depends on whether the variable is signed or unsigned.
Please see C18 §6.3.1.3

Signed and unsigned integers

1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

CodePudding user response:

The C language was designed to be "strongly typed, weakly checked" (direct quote from Dennis Ritchie, one of its authors), meaning that even though all type validation is done at compile time, the compiler will usually pick the path of least resistance when generating machine code. On most architectures, using a 16-bit type simply means that it will use 16-bit load and store instructions for that variable, which will automatically make its value mod(65536). So while the compiler notices that you're trying to put a value that's larger than (2^16)-1 into a 16-bit integer, it also won't really do anything about it. So yes, your variable will contain the value 41248.

CodePudding user response:

does that mean the value is set to 65535, 41248 (which is the remainder of 500000/65536), or another value?

With unsigned types, the value is wrapped (mod 63336).

With signed values, it is implementation defined by the compiler. Commonly, it is also wrapped. Robust portable code does not assume this.

Recommendation: Use unsigned math and types to achieve specified consistent results.

  • Related