Ankit Srivastava
Ankit Srivastava

Reputation: 75

How to convert binary to decimal using BigInteger?

I am trying to print decimal number from binary number using BigInteger class. I am using BigInteger(String val, int radix) constructor of BigInteger class to convert given binary value to decimal but it is printing the exact binary value which is passed in constructor.Waht is the error? The code is as follows:

System.out.print("Ente the decimal number:");
s=String.valueOf(sc.nextInt());

BigInteger i=new BigInteger(s,10);
System.out.println(i);

Upvotes: 0

Views: 3904

Answers (3)

Oghli
Oghli

Reputation: 2340

Actually you are not printing the decimal value of binary number

The value which is printed is the exact decimal representation of String val

According to radix that you put in this statement it will act like this :

 BigInteger i = new BigInteger("11101", 10); // 11101 

11101 this output is actually decimal number not a binary number

In order to get the expected result you should change radix value to 2 after that it will print the decimal value of the binary number:

BigInteger i = new BigInteger("11101", 2);
System.out.println(i);

Output:

29

Upvotes: 3

shmosel
shmosel

Reputation: 50716

To parse the input in binary, use Scanner.nextBigInteger() with a radix of 2:

System.out.print("Enter the decimal number:");
BigInteger i = sc.nextBigInteger(2);
System.out.println(i);

The output will be in decimal by default.

Upvotes: 0

Eran
Eran

Reputation: 393771

If you are trying to parse the input String as a binary, you should write:

BigInteger i=new BigInteger(s,2);

When you print it

System.out.println(i);

it will be displayed in decimal by default.

It doesn't make sense, however, to read the number as int and then convert to String and pass to BigInteger constructor, since that limits the range of numbers that would work.

try:

s = sc.nextLine();
BigInteger i=new BigInteger(s,2);
System.out.println(i);

Upvotes: 0

Related Questions