这不一定是一个编程问题,但我相信你们知道如何做到。我该如何将浮点数转换为二进制?
我要转换的数字是27.625。
27可以表示为11011,但是我应该怎么处理小数部分的.625呢?
在纸上,将十进制数的小数部分转换为二进制数的好算法是“重复乘以2”的算法(详见http://www.exploringbinary.com/base-conversion-in-php-using-bcmath/,“dec2bin_f()”标题下的细节)。例如,0.8125转换为二进制如下:
1. 0.8125 * 2 = 1.625
2. 0.625 * 2 = 1.25
3. 0.25 * 2 = 0.5
4. 0.5 * 2 = 1.0
以下是对我有效的代码,您可以使用此代码转换任何类型的双精度值:
private static String doubleToBinaryString( double n ) {
String val = Integer.toBinaryString((int)n)+"."; // Setting up string for result
String newN ="0" + (""+n).substring((""+n).indexOf("."));
n = Double.parseDouble(newN);
while ( n > 0 ) { // While the fraction is greater than zero (not equal or less than zero)
double r = n * 2; // Multiply current fraction (n) by 2
if( r >= 1 ) { // If the ones-place digit >= 1
val += "1"; // Concat a "1" to the end of the result string (val)
n = r - 1; // Remove the 1 from the current fraction (n)
}else{ // If the ones-place digit == 0
val += "0"; // Concat a "0" to the end of the result string (val)
n = r; // Set the current fraction (n) to the new fraction
}
}
return val; // return the string result with all appended binary values
}