Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get unsigned long long addition carry

I want to get the carry bit of adding two unsigned 64-bit integers in c. I can use x86-64 asm if needed. code:

#include <stdio.h>

typedef unsigned long long llu;

int main(void){
  llu a = -1, b = -1;
  int carry = /*carry of a+b*/;
  llu res = a+b;
  printf("a+b = %llu (because addition overflowed), carry bit = %d\n", res, carry);
  return 0;
}
like image 859
neo5003 Avatar asked May 07 '19 17:05

neo5003


1 Answers

Carry can be only 0 or 1. 1 if there was a wrapping-around and 0 otherwise. The wrapping-around is happening in case a + b > ULONG_LONG_MAX is true . Note, this is in mathematical terms, not in terms of C, as if a + b is actually overflowing, then this will not work. Instead you want to rearrange it to be a > ULONG_LONG_MAX - b. So the value of carry will be:

carry = a > ULONG_LONG_MAX - b ? 1 : 0;

or any preferred style equivalent.

  • Don't forget to include limits.h.
like image 140
Eugene Sh. Avatar answered Sep 30 '22 09:09

Eugene Sh.