Question

I have a very large nanosecond value (representing nanoseconds since epoch) which I try to break down into seconds since epoch and nanoseconds like this:

uint64_t nanosecondsEpoch;
unsigned secs = nanosecondsEpoch / 1000000000ULL;
unsigned nanos = nanosecondsEpoch - (secs * 1000000000ULL);

the problem is if I try to stitch it back together like this:

uint64_t stichBack = secs * 1000000000ULL + nanos

I get something which is way off. I think the reason is that when I perform the division, I get 1357314854.03 for secs and the 0.03 gets dropped (causing the big discrepancy)..but I'm confused because it feels like I should be able to save both pieces of information in an unsigned and recover the information without resorting to floats? Am I doing something plain silly in the arithmetic that I can't seem to catch?

Here is a specific example:

value for nanoseconds since epoch somtime today in the morning: 1357314854032484000

I would use uint64_t if i could for both seconds and nanosecond unsigned, but what I'm wondering is why I can't break the above value as above and put it back together.

Was it helpful?

Solution

Since 1e9 is less than 2^32-1 (maximum unsigned 32-bit integer), if the original value is large enough, the quotient may still be too large to fit in a 32-bit integer. Not sure what your original value is, but it's possible you're truncating your secs value as a result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top