Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Difference of two unsigned 64-bit integer in a signed 64-bit integer

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;
}
like image 863
Abhi Avatar asked Dec 05 '22 18:12

Abhi


1 Answers

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;
}
like image 128
bames53 Avatar answered Dec 07 '22 09:12

bames53