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;
}
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.
limits.h
.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