I have been doing an operation in C++ on the timer struct of Linux provided by the interface "clock_gettime(CLOCK_MONOTONIC, &CurrentTime)"
#include <iostream>
#include <time.h>
int main()
{
struct timespec CurrentTime;
CurrentTime.tv_sec = 28220;
CurrentTime.tv_nsec = 461189000;
unsigned long long TimeNow;
TimeNow = (28220 * 1000000) + (461189000 * 0.001);
std::cout << TimeNow;
}
yet the result always giving TimeNow as a Zero.
I would appreciate if any has answer to this question or a lead to follow. It was done using GCC Compiler
Code Snipped could be found here http://rextester.com/XRR83683
In the line:
the
(28220 * 1000000)part is calculated usingints, and (with 32-bitint) overflows giving an incorrect value (likely -1844771072).The
(461189000 * 0.001)part is calculated usingdoubles, because of the0.001double constant, giving 461189.0 as adouble.The two are then added together, giving a negative
doublevalue... when that negativedoubleis converted tounsigned long longfor the assignment toTimeNow, it's being converted as 0, probably because that's the closest value in its range to any negative number. This is different from converting a negative integer type to unsigned, which would "wrap around".