-1
#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

ashok v
  • 408
  • 3
  • 11

1 Answers1

2

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.

lcs
  • 4,227
  • 17
  • 36
  • 3
    The type of `time_t` is unspecified. Some systems use a signed 32 bit integer for `time_t`; these systems will have a problem in 2038. Other systems use a signed 64 bit integer; they won't have problems until C is a forgotten language. Yet others (C11 compliant) use a real. That's problematic if the real is a float, not so bad if the real is a double. – David Hammen Apr 28 '15 at 17:47
  • @DavidHammen if a 32-bit `int` is a problem, then certainly a 32-bit `float` wouldn't have enough precision even if it has enough range. Is it realistic to expect to run into such an implementation? – Mark Ransom Apr 28 '15 at 17:53
  • @MarkRansom - The C11 standard merely says that `clock_t` and `time_t` "are real types capable of representing times" (7.27.1). To me, that means a vendor can use a 32 bit float. A 32 bit float "can represent time" (just not very well). Whether those vendors have to face the music because of this choice is a different question. – David Hammen Apr 28 '15 at 17:57
  • @DavidHammen: Strictly speaking, complex types are "real types". I'd love to see a system where it makes sense for `time_t` to be a complex type. 8-)} – Keith Thompson Apr 28 '15 at 18:03