I am trying to write a function in C++ which takes two 64 bit unsigned integers and returns their difference in a signed 64 bit integer. It seems to be a bit complicated because of the overflow situation - Since the inputs are two unsigned positive integers, if the absolute difference between these two is greater than maximum signed value (INT64_MAX), then the difference cannot be transmitted through a signed integer. So I have written the following implementation, and I was wondering, first, if this is correct functionally, and second, is there a simpler implementation. Any suggestions would be greatly appreciated. Thanks! (I am going to replace the assert with an exception, it is just there for now!)
int64_t GetDifference(uint64_t first, uint64_t second) {
uint64_t abs_diff = (first > second) ? (first - second): (second - first);
uint64_t msb_abs_diff = (abs_diff >> (sizeof(abs_diff)*8 - 1)) & 1;
assert(msb_abs_diff == 0);
int64_t diff = first - second;
return diff;
}
To me this seems a simpler and more readable implementation.
int64_t GetDifference(uint64_t first, uint64_t second) {
uint64_t abs_diff = (first > second) ? (first - second): (second - first);
assert(abs_diff<=INT64_MAX);
return (first > second) ? (int64_t)abs_diff : -(int64_t)abs_diff;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With