FormatDateTime - Integer arithmetic overflow C++

1

I'm using a C++ builder function which allows me to format a time received from my microcontroller as below:

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);
}

Using this code I get the following warning:

Integer arithmetic overflow

Is there any solution to avoid this issue?

c++
datetime
integer-overflow
asked on Stack Overflow Feb 14, 2020 by geek225 • edited Feb 14, 2020 by Andreas

1 Answer

1

Although some compilers will interpret the constant 0x100000000 as a 64-bit integer, it seems that yours does not - which makes it too big to fit into a 32-bit integer (hence the warning).

A simple way around this is to replace the integer constant with a double value:

FloatingDate += 4294967296.0;

Alternatively (if your compiler supports it) you can add the uLL suffix to the integer constant:

FloatingDate += 0x100000000uLL;

But this may cause a different warning (conversion from unsigned long long to double can cause loss of precision).

answered on Stack Overflow Feb 14, 2020 by Adrian Mole • edited Feb 14, 2020 by Adrian Mole

User contributions licensed under CC BY-SA 3.0