Skip to content

Instantly share code, notes, and snippets.

@focs
Last active December 20, 2016 17:45
Show Gist options
  • Save focs/3399fc6b88eab2b8830c47d7742f070c to your computer and use it in GitHub Desktop.
Save focs/3399fc6b88eab2b8830c47d7742f070c to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cstdint>
inline int64_t secToNano(double sec)
{
constexpr int64_t e9 = 1e9;
const int64_t seconds = sec; // Truncate decimals
const int64_t nanoseconds = (sec - seconds) * e9;
const int64_t time = seconds * e9 + nanoseconds;
return time;
}
inline double nanoToSec(int64_t nano)
{
constexpr int64_t e9 = 1e9;
const int64_t seconds = nano / e9;
const int64_t nanoseconds = nano - seconds * e9;
const double time = static_cast<double>(seconds) + static_cast<double>(nanoseconds) * 1e-9;
return time;
}
int main ()
{
double time = 1349442752.2338988781;
std::cout << (time == nanoToSec(secToNano(time))) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment