c++uint64timeval

I am getting a negative value when I try to convert a uint64_t to struct timeval? //edited


#include <iostream>
#include <sys/time.h> 
#include <stdint.h>

void convert(uint64_t offset )
{
  struct timeval t;
  t.tv_sec = offset / 1000000;
  std::cout <<  "currentTimeOffset " << offset << "startTimeOffset " << t.tv_sec  << std::endl;
  t.tv_usec =  offset % 1000000;
  std::cout <<  "stattime usec " <<  t.tv_usec << std::endl ;
}

int main(int argc , char** argv)
{    
  uint64_t t = 18446744073709551615;
  convert(t );
  return 0;
}

Is there a rounding error ? How do I accomplish this then ? This is a routine that is called from elsewhere the code is in convert. I wrote a small script with an example of the uint64_t that is giving me a negative number


Solution

  • offset / 1000000 produces a value of 1.8446744073709551615 × 10^13 which is too large for tv_sec which is of type int32. The max value that can be stored in an int32 is 2.147483647 × 10^9.

    You're overflowing the integer you're storing the result in, and it is wrapping around and becoming negative.