Chillax
Chillax

Reputation: 4698

Binary addition of Strings

I need to combine an array of strings as below ( so as each character in the result string is a bitwise & of the characters in the input string)

String a = "10110001"
String b = "01101101"
String c = "10101011"

String result = "00100001"

Solution I came up with:

long resultLong = 0;

for( String a : inputs )
{
    resultLong = resultLong & Long.parseLong( a ,2);
}

String result = Long.toBinaryString( resultLong );

The number of characters in the input string could be very long, and the above solution wouldn't work (NumberFormatException) . I couldn't get my head around how to implement this, what would be the cleanest way ?

Upvotes: 2

Views: 73

Answers (2)

Shubhendu Pramanik
Shubhendu Pramanik

Reputation: 2751

Here's your algorithm. This will work for any number of Strings provided that all the Strings are of same length:

public static void main(String[] args) {
    String a = "10110001";
    String b = "01101101";
    String c = "10101011";

    String arr[] = new String[]{a, b, c};

    String finalString = "";
    for (int i = 0; i < arr[0].length(); i++) {
        int temp = Integer.parseInt("" + arr[0].charAt(i));
        for (int j = 1; j < arr.length; j++) {
            temp = temp & Integer.parseInt("" + arr[j].charAt(i));
        }
        finalString += temp;
    }
    System.out.println(finalString);
}

O/P

00100001

Upvotes: 0

Amit Bera
Amit Bera

Reputation: 7315

If Long is not enough for your use case then you can use BigInteger

BigInteger(String val, int radix);

Which takes a String and radix as the arguments.

BigInteger result = new BigInteger(inputs[0], 2);

for (int i = 1; i < inputs.length; i++) {
    result = result.and(new BigInteger(inputs[i], 2));
}

String resultStr = result.toString(2);

Upvotes: 3

Related Questions