Add binary numbers like decimal numbers in Java. eg 0101 + 0110 = 0211

868 views Asked by At

I needed to write a program which adds binary numbers as if they were decimal. But it isn't working like I expected.

int i = 0101, j=0001;
System.out.println(i+j);

I expected the answer to be either 6 (i.e decimal of sum of 0101 and 0001) or maybe 0102 (as I am adding them as simple decimal numbers). But unexpectedly, I am getting 66. Can anybody kindly explain this? Or may be help me with the code to add two binary numbers as decimal numbers.

2

There are 2 answers

2
Anindya Dutta On
int num1 = Integer.parseInt(Integer.toString(i),2);
int num2 = Integer.parseInt(Integer.toString(j),2);
System.out.println(num1+num2);

First we need to convert the number from binary to decimal. And for that you need to parse it using the parse commands for the Integer wrapper class. Then you can add.

The format Integer.parseInt(String,radix) can be used to convert any string of digits to the base radix.

2
fabian On

You're using octal literals, i.e. 0101 = 65 = 1 * 8² + 1. To use binary literals use the following notation:

int i = 0b101, j = 0b1;

If you want to print a int as binary, use Integer.toBinaryString to get the string representation of a int in binary.