转换二进制表示?

我有下面的问题,所以我试图将一个双重转换为它的二进制表示,但使用这个Long.toBinaryString(Double.doubleToRawLongBits(d))没有帮助,因为我有大数字,龙不能存储它们即2^900

感谢任何帮助:)。

Long.toBinaryString(Double.doubleToRawLongBits(d))似乎工作得很好。

 System.out.println("0: 0b" + Long.toBinaryString(Double.doubleToRawLongBits(0D))); System.out.println("1: 0b" + Long.toBinaryString(Double.doubleToRawLongBits(1D))); System.out.println("2: 0b" + Long.toBinaryString(Double.doubleToRawLongBits(2D))); System.out.println("2^900: 0b" + Long.toBinaryString(Double.doubleToRawLongBits(Math.pow(2, 900)))); System.out.println("Double.MAX_VALUE: 0b" + Long.toBinaryString(Double.doubleToRawLongBits(Double.MAX_VALUE))); /* prints: 0: 0b0 1: 0b11111111110000000000000000000000000000000000000000000000000000 2: 0b100000000000000000000000000000000000000000000000000000000000000 2^900: 0b111100000110000000000000000000000000000000000000000000000000000 Double.MAX_VALUE: 0b111111111101111111111111111111111111111111111111111111111111111 */ 

你可能想要处理整个和小数部分:

 public String toBinary(double d, int precision) { long wholePart = (long) d; return wholeToBinary(wholePart) + '.' + fractionalToBinary(d - wholePart, precision); } private String wholeToBinary(long l) { return Long.toBinaryString(l); } private String fractionalToBinary(double num, int precision) { StringBuilder binary = new StringBuilder(); while (num > 0 && binary.length() < precision) { double r = num * 2; if (r >= 1) { binary.append(1); num = r - 1; } else { binary.append(0); num = r; } } return binary.toString(); } 

你有没有尝试过使用java.math.BigInteger和调用toString(int radix)的参数为2?

您可以使用BigInteger来保存您的大数字,并使用BigInteger.toString()方法来检索它的二进制表示。

 BigInteger bigNum = new BigInteger(sYourNum); System.out.println( bigNum.toString(2) ); 

要打印小数部分,我们可以乘以2,并检查它是否大于等于1.这实质上是移动小数和。

 public static String binary(double num){ if(num>=1 || num <=0){ return "ERROR"; } StringBuilder binary = new StringBuilder(); binary.append("."); while(num>0){ /* Setting up the limit to the 32 characters */ if(binary.length()>=32) return "ERROR"; double r=num*2; if(r>=1){ binary.append(1); num=r-1; }else { binary.append(0); num=r; } } return binary.toString(); } 

您可以使用Double.toHexString(d),然后使用for循环和StringBuilder将hexstring转换为二进制string。