手动将浮点数转换为二进制格式

时间:2014-01-27 17:29:37

标签: java algorithm binary numbers binaryformatter

嗨我在基数10中有以下浮点值: 0.625 。我需要将基数10中的这个值转换为二进制格式,即: 0.101 。 我找到的算法如下。它有效,但我不明白为什么会这样。有人可以解释为什么下面的代码有效吗?我知道小数点后面的数字的计算方式是1/2 ^ n,其中n是从小数点开始计算的。感谢。

为了澄清,我需要知道数学公式背后的原因。没有单步执行代码。

private static String floatToBinaryString( double n ) {
    String val = "0.";
    while ( n > 0 ) {
        double r = n * 2;
        if( r >= 1 ) {
            val += "1";
            n = r - 1;
        }else{
            val += "0";
            n = r;
        }
    }
    return val;
}

1 个答案:

答案 0 :(得分:3)

将该分数乘以2并使用位数位作为二进制值,直到分数等于零。示例如下。

这是使用0.625进行转换的标准公式:

1) Multiply fraction by 2 =>  0.625 * 2 = 1.25
    The digit to the left of the decimal point is the first binary value, 0.1 so far
2) Ignore the ones-place digit and you have 0.25 which is still larger than zero.
    Multiply the fraction by 2 => 0.25 * 2 = 0.50
    The digit to the left of the decimal point is the next binary value, 0.10 so far
3) Ignore the ones-place digit and you have 0.50 which is less than zero.
    Multiply the fraction by 2 => 0.5 * 2 = 1.00
    The digit to the left of the decimal point is the next binary value, 0.101 so far
4) Ignore the ones-place digit and you have 0.00 which is equal to zero.
    Conversion complete!

private static String floatToBinaryString( double n ) {
    String val = "0.";    // Setting up string for result
    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
}