【问题标题】:Manually convert float point number into binary format手动将浮点数转换为二进制格式
【发布时间】:2014-02-18 16:29:09
【问题描述】:

您好,我有以下以 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;
}

【问题讨论】:

  • 看起来不像你在base 10中拥有它
  • 我建议你在调试器中单步调试代码,看看每一行代码的作用。
  • 我知道每一行代码的作用,我已经说过它有效。我想知道它为什么有效。数学公式背后的原因是什么。
  • 您可能已经将所有代码都排除在外,并用类似这样的措辞...“将基数 10 分数转换为基数 2 的数学公式背后的原因是什么?”。跨度>

标签: java algorithm binary numbers binaryformatter


【解决方案1】:

您将分数乘以 2 并使用个位数字作为二进制值,直到分数等于 0。下面的例子。

这是使用您拥有的 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
}

【讨论】:

  • 我的问题是为什么“将当前分数 (n) 乘以 2”。我知道所有步骤,这很直观。我的问题是数学公式背后的推理。
  • 道歉。您的问题中的短语“我找到的算法如下。它有效,但我不明白为什么会这样。有人可以解释一下为什么下面的代码有效吗?”让我相信你不明白代码是如何工作的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 2014-11-24
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
相关资源
最近更新 更多