c++ - FormatDateTime-整数算术溢出C++

标签 c++ datetime integer-overflow

我正在使用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/

相关文章:

c++ - 难以理解 Scheme 中 let 和 lambda 的用法

c++ - 在 C++ 中创建 n 个项目的所有可能的 k 个组合

javascript - 现在有多少位可用于 JS 风格的 "integer"数学?

c - 当我的程序看到一个不影响程序运行的整数溢出时应该怎么办?

c++ - 如何安全地比较两个无符号整数计数器?

c++ - 立方体在 OpenGL 中的位置

c++ - EXC_BAD_ACCESS 从 NSTimer 调用 c++ 类方法

datetime - 日期/时间值的可移植二进制表示

sql - 在非常大的表中选择最近的值

python - "2016-10-22T16:27:54+0000"格式转换为日期时间