简体   繁体   中英

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);

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

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM