整数转换导致截断

Integer conversion resulted in truncation

在嵌入式 C 中,我只是将 500000 的值输入到一个 16 位槽中。它给了我“整数转换导致截断”的警告。在这种情况下,这是否意味着该值设置为 65535、41248(即 500000/65536 的余数)或其他值?还是这里没有提供足够的信息来确定它的价值,还有其他因素在起作用?如果需要更多信息,请告诉我。

(示例代码,以防有帮助)

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

C 语言被设计为“强类型、弱检查”(直接引自其作者之一丹尼斯·里奇),这意味着即使所有类型验证都在编译时完成,编译器通常会选择生成机器代码时阻力最小的路径。在大多数体系结构中,使用 16 位类型仅意味着它将对该变量使用 16 位加载和存储指令,这将自动使其值 mod(65536)。因此,尽管编译器注意到您试图将大于 (2^16)-1 的值放入 16 位整数中,但它实际上也不会对此做任何事情。所以是的,您的变量将包含值 41248.

这取决于变量是有符号的还是无符号的。
请参阅 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.

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

对于 unsigned 类型,值被换行 (mod 63336)。

有符号值,是编译器定义的实现。通常,它也被包裹起来。健壮的可移植代码不假设这一点。

建议:使用无符号数学和类型来获得指定的一致结果。