我正在使用C++构建器函数,该函数可以格式化从微 Controller 接收的时间,如下所示:
void DisplayTime(unsigned long SecondsSince1900, unsigned short FractionOfSecond, AnsiString* DecodedString)
{
TDateTime WindowsDate;
double FloatingDate;
FloatingDate = SecondsSince1900 + (FractionOfSecond / 65536.0);
if ( (SecondsSince1900 & 0x80000000) == 0 )
{// Seconds since wraps around during year 2036.
// When the top bit is clear we assume that the date is after 2036 rather than before 1968.
FloatingDate += 0x100000000;//this line is the cause of the warning
}
FloatingDate /= SECONDS_IN_DAY ;
WindowsDate = FloatingDate ;
*DecodedString = FormatDateTime(" yyyy/mm/dd hh:mm:ss ", WindowsDate);
}
使用此代码,我得到以下警告:
Integer arithmetic overflow
有什么解决方案可以避免此问题?
最佳答案
尽管有些编译器会将常量0x100000000
解释为64位整数,但您似乎并不理解-这使得它太大而无法容纳32位整数(因此警告)。
解决此问题的一种简单方法是用double
值替换整数常量:
FloatingDate += 4294967296.0;
另外(如果编译器支持),可以将
uLL
后缀添加到整数常量中:FloatingDate += 0x100000000uLL;
但这可能会导致不同的警告(从
unsigned long long
转换为double
可能会导致精度降低)。
关于c++ - FormatDateTime-整数算术溢出C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60224140/