Reputation: 25
I have a task to convert a 64-bit binary floating-point number into a base 10 decimal. An example here:
Input: 64-bit binary floating-point number: 0100000000001001001000011111101101010100010001000010110100011000
Output: Base 10 Decimal: 3.14
what I know here, first character is a sign = 0 (positive) , 1(negative). Next 11 bits represent the exponent, and the rests are Mantissa.
My problem is I don't know the math equation or the math solution to convert it. I am going to solve this task using Java.
Upvotes: 0
Views: 1567
Reputation: 40034
Here is the explanation. As you already stated, the main parts are:
- sign = 0
- exponent = 10000000000
- mantissa = 1001001000011111101101010100010001000010110100011000
Since all mantissa values are shifted left (normalized) until the first bit is a 1
, that bit can be implied. So the actual mantissa prefixed with a 1
, the value would be
- mantissa = 11001001000011111101101010100010001000010110100011000
The base offset for the exponent is 1023
. The exponent above is 1024
so the exponent would be 1
+ an additional 1
for the implied bit.
.11 x 2
2
So the whole number part would be binary 11
or decimal 3
.
double whole = 3;
The rest of the mantissa is the fractional part and starts where the whole number stopped.
fraction = 001001000011111101101010100010001000010110100011000
so given a string of bits as above, the fractional part can be added to the whole by dividing each successive bit by ever increasing powers of 2. (e.g. 0/2 + 0/4 + 1/8 + etc)
double div = 1.;
for (char c : fract.toCharArray()) {
div*=2.;
whole += (c-'0')/div;
}
System.out.println(whole);
prints
3.141592653589793
Note: The above was cheating somewhat in that it used a double to compute the fractional part. There are more involved methods to emulate floating point math but the purpose here was to demonstrate extracting the bit fields to create a double value. If I were doing this I would use the methods described in the other answers.
Upvotes: 0
Reputation: 1500215
Convert the binary into a long
value - you can use Long.parseLong(text, 2)
for that if you've got the binary value as a string... and then Double.longBitsToDouble
to perform the conversion to a double
. For example:
public class Test {
public static void main(String[] args) {
String text = "0100000000001001001000011111101101010100010001000010110100011000";
long parsedAsLong = Long.parseLong(text, 2);
double converted = Double.longBitsToDouble(parsedAsLong);
System.out.println(converted);
}
}
Upvotes: 1
Reputation: 198033
Double.longBitsToDouble(long)
takes a 64-bit long and converts it to a floating point double, which you can then print.
Given that, you can just use Long.parseLong(binary, 2)
to convert a string of 0s and 1s to a long, and then use that method to get a floating point value.
Upvotes: 1