繁体   English   中英

如何使用BigInteger将二进制转换为十进制?

[英]How to convert binary to decimal using BigInteger?

我正在尝试使用BigInteger类从二进制数打印十进制数。 我正在使用BigInteger类的BigInteger(String val,int radix)构造函数将给定的二进制值转换为十进制,但它正在打印在构造函数中传递的确切二进制值。这是错误吗? 代码如下:

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

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

实际上,您不是在打印二进制数的十进制值

打印的值是String val的精确十进制表示形式

根据您在此语句中输入的radix ,它的行为如下:

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

11101此输出实际上是十进制数而不是二进制数

为了获得预期的结果,您应该将radix数值更改为2之后它将输出二进制数的十进制值:

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

输出

29

如果尝试将输入字符串解析为二进制,则应编写:

BigInteger i=new BigInteger(s,2);

打印时

System.out.println(i);

默认情况下,它将以十进制显示。

但是,将数字读取为int然后转换为String并传递给BigInteger构造函数没有任何意义,因为这限制了可以使用的数字范围。

尝试:

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

要解析二进制输入,请使用Scanner.nextBigInteger() ,其基数为2:

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

默认情况下,输出为十进制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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