0

I have a method below which will accept oldTimestamp as the input parameter which is uint64_t... Now I need to apply a formula on the above oldTimestamp and whenever I apply that formula, I always get 0 as start value.

And also I try to get the current timestamp in milliseconds in the same method which is long int data type (not sure whether this is right datatype) and whenever I apply the same formula again on the currentTimestamp, I always get end value as 0 as well...

Below is my method -

void getRecord(uint64_t oldTimestamp) {

    int start = (oldTimestamp / (60 * 60 * 1000 * 24))  % 14;

    cout<<"START: " << start <<endl; // this always print out as 0..?

    struct timeval tp;
    gettimeofday(&tp, NULL);

    long int currentTimestamp = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds

    int end = (currentTimestamp / (60 * 60 * 1000 * 24))  % 14;

    cout<<"END: " << end <<endl; // this always print out as 0 as well..?

}

Is there anything wrong I am doing here?

Might be, I am using wrong Data Type for currentTimestamp and oldTimestamp and I should not use int for start and end?

Update:-

Something like this will be fine?

void getRecord(uint64_t oldTimestamp) {

    uint64_t start = (oldTimestamp / (60 * 60 * 1000 * 24))  % 14;

    cout<<"START: " << start <<endl;

    struct timeval tp;
    gettimeofday(&tp, NULL);

    uint64_t currentTimestamp = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds

    uint64_t end = (currentTimestamp / (60 * 60 * 1000 * 24))  % 14;

    cout<<"END: " << end <<endl;

}

2 Answers2

1
void getRecord(uint64_t oldTimestamp) { // you are using uint64_t here

int start = (oldTimestamp / (60 * 60 * 1000 * 24))  % 14; // you are using int here

You are likely running into an overflow issue, which is invoking undefined behavior.

You need to use uint64_t as your start type. The same goes for your currentTimestamp and end variables.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • I updated my question with the correct code.. Can you take a look and let me know if everything looks good to you? –  Oct 24 '13 at 21:33
  • You may also want to add the proper suffixes to your constants: `60LL * 60LL * 1000LL * 24LL`, etc. I would also suggest you actually do the math and use a single constant (though, your compiler will likely do that for you ... it just makes it more readable to have a single constant instead of carrying around a constant expression literal everywhere). – Zac Howland Oct 25 '13 at 00:17
0

The problem is that you're using int for start and end.

m3h2014
  • 156
  • 5