I would just use your approach using BigInteger. I'm using Random to just generate values that are randomly signed for demonstration.
Random r = new Random();
for (int i = 0; i < 10; i++) {
String a = (r.nextBoolean()?"": "-")+Integer.toBinaryString(r.nextInt(100));
String b = (r.nextBoolean()?"": "-")+Integer.toBinaryString(r.nextInt(100));
String result = addBinary(a,b);
System.out.printf("%10s + %10s = %s%n",a,b,result);
}
prints something like
-11000 + -101111 = -1000111
101011 + -101 = 100110
-0 + 110 = 110
-1001101 + -101 = -1010010
-1000 + 10100 = 1100
-111011 + -1001111 = -10001010
110011 + -10100 = 11111
110010 + 1001011 = 1111101
10111 + 1010111 = 1101110
-111001 + 101100 = -1101
The modified method
public static String addBinary(String a, String b) {
BigInteger ba = new BigInteger(a,2);
BigInteger bb = new BigInteger(b,2);
return ba.add(bb).toString(2);
}
Since BigInteger has arbitrary precision, negative binary numbers are shown simply as negative and not in 2's complement form.