0

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));
asked Jun 20, 2015 at 23:08
21
  • How are you distinguishing what you consider to be a "binary number" and what you consider to be a "decimal number"? Commented Jun 20, 2015 at 23:11
  • Binary numbers contains 0 and 1. Decimal numbers contains 0,1,2,3,4,5,6,7,8,9. Commented Jun 20, 2015 at 23:14
  • Is this what you are looking for? Commented Jun 20, 2015 at 23:16
  • @silent_rain I don't think you are getting my point. You have a number inside a computer. It will generally be represented in binary - even BigDecimal does not actually store strings of [0,9]. What do you require to make you consider something a decimal number? Commented Jun 20, 2015 at 23:18
  • 1
    It gives me result in decimal.. For example, when I put 11+11, I get 6 as result.. It is true, 11+11=110 (110=6 in decimal). But, I need binary as result, I need to get 110 not 6... Commented Jun 20, 2015 at 23:33

1 Answer 1

4

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
answered Jun 20, 2015 at 23:46

2 Comments

Thanks for reply... but, i tried this, and stored result as String but I get 6 again... I don't know why is it...
Note that an int is always stored in binary. So do long, float, double. BigDecimal is not, and stored in it's base 10 form or decimal form. By default, when converting an int to a String, it will be transformed using base 10 (decimal form, or 0-9 characters). To store it as a String in it's binary form (1 and 0 characters), you always have to call the Integer.toBinaryString as shown on this answer.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.