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));
-
How are you distinguishing what you consider to be a "binary number" and what you consider to be a "decimal number"?Patricia Shanahan– Patricia Shanahan2015年06月20日 23:11:22 +00:00Commented 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.silent_rain– silent_rain2015年06月20日 23:14:38 +00:00Commented Jun 20, 2015 at 23:14
-
Is this what you are looking for?Turing85– Turing852015年06月20日 23:16:51 +00:00Commented 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?Patricia Shanahan– Patricia Shanahan2015年06月20日 23:18:33 +00:00Commented Jun 20, 2015 at 23:18
-
1It 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...silent_rain– silent_rain2015年06月20日 23:33:35 +00:00Commented Jun 20, 2015 at 23:33
1 Answer 1
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
silent_rain
Thanks for reply... but, i tried this, and stored result as String but I get 6 again... I don't know why is it...
YoYo
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.lang-java