Java:BigInteger到Binary的字符串

时间:2014-06-17 17:03:57

标签: string binary java.util.scanner biginteger

我有一个问题,我想将输入字符串转换为BigInteger,输出应该是二进制字符串。我使用了这段代码,但它只能读取“0”和“1”。

Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
BigInteger big = new BigInteger(input, 2);
String binarystring = big.toString(2);
System.out.println(binarystring);

当我将其更改为:BigInteger big = new BigInteger(input, 16);时 我可以用十六进制数写,但没有空格。

我想要的是我可以写任何字符串,程序应该在字符串中给我二进制值。

1 个答案:

答案 0 :(得分:0)

像“hey world”这样的字符串在base 10中没有任何有意义的数字表示,所以我建议输出一个合适的消息。

Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
try {
    BigInteger big = new BigInteger(input); // default constructor is base 10
    System.out.println(big.toString(2));
}
catch (NumberFormatException){
    System.out.println("Input was not a decimal number");
}
相关问题