Skip to content

Instantly share code, notes, and snippets.

@kishida
Created January 23, 2016 17:03
Show Gist options
  • Save kishida/95f1fb4d2aa48245b59e to your computer and use it in GitHub Desktop.
Save kishida/95f1fb4d2aa48245b59e to your computer and use it in GitHub Desktop.
Add only with logical operation.
public class Add {
public static void main(String[] args) {
int a = 0b01100101;
int b = 0b00110110;
System.out.printf("a:%d b:%d a+b:%d%n", a, b, a + b);
int and = a & b;
System.out.printf("%8s(%d)%n", Integer.toBinaryString(a), a);
System.out.printf("%8s(%d)%n", Integer.toBinaryString(b), b);
System.out.printf("%8s(%d) xor%n", Integer.toBinaryString(a ^ b), a ^ b);
System.out.printf("%8s(%d) and%n", Integer.toBinaryString(and), and);
System.out.println();
a = a ^ b;
b = and << 1;
and = a & b;
System.out.printf("%8s(%d) and << 1%n", Integer.toBinaryString(b), b);
System.out.printf("%8s(%d) xor%n", Integer.toBinaryString(a ^ b), a ^ b);
System.out.printf("%8s(%d) and%n", Integer.toBinaryString(and), and);
System.out.println();
a = a ^ b;
b = and << 1;
and = a & b;
System.out.printf("%8s(%d) and << 1%n", Integer.toBinaryString(b), b);
System.out.printf("%8s(%d) xor%n", Integer.toBinaryString(a ^ b), a ^ b);
System.out.printf("%8s(%d) and%n", Integer.toBinaryString(and), and);
System.out.println();
}
}
@kishida
Copy link
Author

kishida commented Jan 23, 2016

a:101 b:54 a+b:155
 1100101(101)
  110110(54)
 1010011(83) xor
  100100(36) and

 1001000(72) and << 1
   11011(27) xor
 1000000(64) and

10000000(128) and << 1
10011011(155) xor
       0(0) and

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment