Java 将 BigInteger 转换为二进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20761983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:07:54 来源:igfitidea点击:
Converting BigInteger to binary string
提问by Kailash
Can we convert Biginteger to binary string
我们可以将 Biginteger 转换为二进制字符串吗
String s1 = "0011111111101111111111111100101101111100110000001011111000010100";
String s2 = "0011111111100000110011001100110011001100110011001100110011001100";
BigInteger bi1, bi2, bi3;
bi1 = new BigInteger(s1,2);
bi2 = new BigInteger(s2,2);
bi3 = bi1.xor(bi2);
How to convert bi3 to binary string
如何将bi3转换为二进制字符串
采纳答案by dasblinkenlight
回答by Riven Flows
import java.math.BigInteger; import java.util.Scanner;
导入 java.math.BigInteger; 导入 java.util.Scanner;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a Number: ");
String n = in.next();
BigInteger nn = new BigInteger(n);
if(nn.compareTo(BigInteger.ZERO)<0){
System.out.println("Number cannot be less than 0");
}else{
System.out.println("Convert to binary is:");
print2Binaryform(nn);
System.out.println("");
}
}
private static void print2Binaryform(BigInteger number) {
BigInteger reminder2;
if(number.compareTo(BigInteger.ONE)<=0){
System.out.print(number);
return;
}
reminder2 = number.mod(new BigInteger(""+2));
print2Binaryform(new BigInteger(""+number.divide(new BigInteger("2"))));
System.out.print(reminder2);
}