问题描述
您好我都按照基础10浮点值: 0.625 。我需要转换以10为二进制格式该值是: 0.101 。算法我发现如下。它的工作原理,但我不理解为什么这个工程。可能有人请解释低于工程为什么code?据我所知,小数点后的数字计算的方式,使得1/2 ^ n,其中n是从小数点计数。谢谢你。
Hi I have following float point value in base 10: 0.625. I need to convert this value in base 10 to binary format which is: 0.101.Algorithm I found is below. It works, but I am not understanding why this works. Could someone please explain to be why the code below works? I am aware that numbers after the decimal point is computed in the manner such that 1/2^n where n is count from the decimal point. Thanks.
要澄清一下,我需要知道的数学公式背后的原因。不步进通过code。
To clarify, I need to know the reasoning behind the mathematical formula. Not stepping through the code.
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;
}
推荐答案
您乘以2馏分并使用个位数字为二进制值,直到馏分等于零。下面的例子。
You multiply the fraction by 2 and use the ones place digit as the binary values until the fraction is equal to zero. Example below.
这是标准的公式使用转换的0.625有:
This is the standard formula for conversion using the 0.625 you have:
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
}
这篇关于手动转换浮点数字转换成二进制格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!