Skip to content

Instantly share code, notes, and snippets.

@OrangeTide
Created June 27, 2011 21:27
Show Gist options
  • Save OrangeTide/1049882 to your computer and use it in GitHub Desktop.
Save OrangeTide/1049882 to your computer and use it in GitHub Desktop.
add without using +,++ or -,--
/* otadd0.c : add without using +,++ or -,-- */
/* clean:
int add(int a, int b)
{
int r,n,c;
for(r=c=0,n=1;n;n<<=1) {
c = (a & b) ^ (c & (a ^ b));
c <<= 1;
r |= (a ^ b ^ c) & n;
}
return r;
}
*/
/* compressed */
int add(int a,int b){
int r,n,c;for(r=c=0,n=1;n;n<<=1){c=(a&b)^(c&(a^b));c<<=1;r|=(a^b^c)&n;}return r;
}
/** test code **/
/* to use:
* ./otadd0 33 66
* ./otadd0 -5 -3
* ...
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
printf("%d\n",add(strtol(argv[1],0,0),strtol(argv[2],0,0)));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment