将双精度转换为二进制表示形式?
2022-09-04 05:56:39
我试图将双精度转换为其二进制表示,但是使用这个没有帮助,因为我有大数字,Long无法存储它们,即.Long.toBinaryString(Double.doubleToRawLongBits(d))
2^900
我试图将双精度转换为其二进制表示,但是使用这个没有帮助,因为我有大数字,Long无法存储它们,即.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();
}