Last active
December 27, 2016 04:46
-
-
Save willeccles/0f197a31bc33a4549c2f704b1c056133 to your computer and use it in GitHub Desktop.
Add and subtract numbers using bitwise operators :D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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