Skip to content

Instantly share code, notes, and snippets.

@willeccles
Last active December 27, 2016 04:46
Show Gist options
  • Save willeccles/0f197a31bc33a4549c2f704b1c056133 to your computer and use it in GitHub Desktop.
Save willeccles/0f197a31bc33a4549c2f704b1c056133 to your computer and use it in GitHub Desktop.
Add and subtract numbers using bitwise operators :D
// add a and b
int binadd(int a, int b) {
int carry = (a & b) << 1;
int result = a ^ b;
if (carry == 0)
return result;
else
result = binadd(result, carry);
return result;
}
// subtract b from a
int binsub(int a, int b) {
// binadd(~b, 1) = two's complement of b, AKA -b
return binadd(a, binadd(~b, 1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment