Last active
December 22, 2017 21:34
-
-
Save psy0rz/a6c7eef831e251997ed82194274f9fb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
long timeDiff(unsigned long prev, unsigned long next) | |
{ | |
long signed_diff = 0; | |
// To cast a value to a signed long, the difference may not exceed LONG_MAX | |
const unsigned long half_max_unsigned_long = 2147483647u; // = LONG_MAX | |
if (next >= prev) { | |
const unsigned long diff = next - prev; | |
if (diff <= half_max_unsigned_long) { | |
// 0........prev******next......................ULONG_MAX | |
// Normal situation, just return the difference. | |
// Difference is a positive value. | |
signed_diff = static_cast<long>(diff); | |
} else { | |
//would expect this: | |
// 0....prev***************************next.....ULONG_MAX | |
//code below retruns this as a negtaive: | |
// 0****prev...........................next*****ULONG_MAX | |
// prev has overflow, return a negative difference value | |
signed_diff = static_cast<long>((ULONG_MAX - next) + prev + 1u); | |
signed_diff = -1 * signed_diff; | |
} | |
} else { | |
// next < prev | |
const unsigned long diff = prev - next; | |
if (diff <= half_max_unsigned_long) { | |
// 0........next******prev......................ULONG_MAX | |
// Normal situation, return a negative difference value | |
signed_diff = static_cast<long>(diff); | |
signed_diff = -1 * signed_diff; | |
} else { | |
//would epect this (negative number) | |
// 0....next***************************prev.....ULONG_MAX | |
//code below returns (positive number): | |
// 0****next...........................prev*****ULONG_MAX | |
// next has overflow, return a positive difference value | |
signed_diff = static_cast<long>((ULONG_MAX - prev) + next + 1u); | |
} | |
} | |
return signed_diff; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment