Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding binary numbers

Tags:

Does anyone know how to add 2 binary numbers, entered as binary, in Java?

For example, 1010 + 10 = 1100.

like image 211
PulsePanda Avatar asked Dec 17 '11 23:12

PulsePanda


People also ask

How does adding binary numbers work?

Binary addition is much like your normal everyday addition (decimal addition), except that it carries on a value of 2 instead of a value of 10. For example: in decimal addition, if you add 8 + 2 you get ten, which you write as 10; in the sum this gives a digit 0 and a carry of 1.


1 Answers

Use Integer.parseInt(String, int radix).

 public static String addBinary(){
 // The two input Strings, containing the binary representation of the two values:
    String input0 = "1010";
    String input1 = "10";

    // Use as radix 2 because it's binary    
    int number0 = Integer.parseInt(input0, 2);
    int number1 = Integer.parseInt(input1, 2);

    int sum = number0 + number1;
    return Integer.toBinaryString(sum); //returns the answer as a binary value;
}
like image 167
Martijn Courteaux Avatar answered Sep 21 '22 16:09

Martijn Courteaux