Adding binary numbers Java

2.1k Views Asked by At

I need to add binary numbers in Java. I tried on this way as below is written, the result is correct, but result is decimal number. Does anyone know how to get result as binary number?

Thanks in advance

private int number2;
private int number2;
private int result;

number1 = Byte.parseByte(String.valueOf(display.getText()));
number2 = Byte.parseByte(String.valueOf(display.getText()));
result = getDecimalFromBinary(number1) + getDecimalFromBinary(number2);
display.setText(Integer.toBinaryString(result));
1

There are 1 best solutions below

2
On BEST ANSWER

Your example seems to be incomplete, because Integer.parseInt(int, int) and Integer.toBinaryString(int) are what you need. Perhaps you aren't storing result as a String. For example,

int a = Integer.parseInt("11", 2);
int b = Integer.parseInt("11", 2);
String result = Integer.toBinaryString(a + b)
System.out.println(result);

Output is (as requested)

110