# java – how to two binary strings, return their sum (also a binary string)

## java – how to two binary strings, return their sum (also a binary string)

To exceed the `long` size you will need `BigInteger`.

``````public void test() {
String a = 100;
String b = 11;
BigInteger bA = new BigInteger(a, 2);
BigInteger bB = new BigInteger(b, 2);
System.out.println(a +  +  + b +  =  + bA.add(bB).toString(2));
}
``````

This does not help with `double` though.

For double you can try this:

``````double number = 2.2;
Long.toBinaryString(Double.doubleToLongBits(number));
``````

#### java – how to two binary strings, return their sum (also a binary string)

https://stackoverflow.com/a/8272792/6049590

Copied and modified from above Source

``````public double ConvertToDouble(string str){
long v = 0;
for (int i = str.Length - 1; i >= 0; i--) v = (v << 1) + (str[i] - 0);
return = BitConverter.ToDouble(BitConverter.GetBytes(v), 0);
}
``````

https://social.msdn.microsoft.com/Forums/vstudio/en-US/0ff76c9a-8d8c-46f3-94cc-420f719a14e4/how-to-convert-floatdoubleulong-into-binaryotcalhex-string?forum=netfxbcl

Copied and modified from above Source

``````public string ConvertToString(double value){
string s = String.Empty;

foreach (byte b in BitConverter.GetBytes(value))
{
s += Convert.ToString(b,2).PadLeft(8,0); // for hex. For binary, use 2 and 8. For octal, use 8 and 3
}
return s;
}
``````

And now the last one:

``````double c = ConvertToDouble(a) + ConvertToDouble(b);
string bitString = ConvertToString(c);
``````

string bitString should be your expected result.