views:

1559

answers:

6

I need to convert 0.5 in base 10 to base 2 (0.1). I have tried using

Double.doubleToRawLongBits(0.5)

and it returns 4602678819172646912 which I guess is in hex, but it does not make sense to me.

A: 

My original post wasn't helpful -- will think about it some more.

Joel Marcey
There's no corresponding Double.toBinaryString(), so it doesn't look that helpful, does it ?
Brian Agnew
yes this is not helpful..
idober
Crap. Yeah, I read through the question too quickly. Sorry.
Joel Marcey
+1  A: 

This is decimal for 0x3FE0_0000_0000_0000. The mantissa is the list of zeros after 3FE (which codes sign and exponent). This is what you are looking for, given that 0.1 before the zeros is implicit.

mouviciel
Ok, how to i convert 0x3FE0_0000_0000_0000 to the string "0.1"?
idober
This is IEEE 754 standard. Look at: http://en.wikipedia.org/wiki/IEEE_754-1985
mouviciel
+6  A: 

No. 4602678819172646912 is in dec, hex is 0x3fe0000000000000. To dismantle that:

   3   |   F   |   E   |  0 ...
0 0 1 1 1 1 1 1 1 1 1 0 0 ...
s|  exponent         |  mantissa

s is the sign bit, exponent is the exponent shifted by 2^9 (hence this exponent means -1), mantissa is the xxx part of the number 1.xxx (1. is implied). Therefore, this number is 1.000...*2^-1, which is 0.5.

Note that this describes the "normal" numbers only, so no zeros, denormals, NaNs or infinities

jpalecek
Can you please give me code that takes 0.5 in base 10 and gives me "0.1" (base 2)
idober
A: 

0.1 is NOT a binary representation of 0.5

Java will represent 0.5 using IEEE 754, as specified on the Java Language Specification. BigInteger.valueOf(Double.doubleToRawLongBits(0.5)).toByteArray() will give you a byte per byte representation of 0.5 as Java does internally.

Marcelo Morales
"0.1 is NOT a binary representation of 0.5" -- Well, it is, but it's not the IEEE 754 representation. Those are not the same thing.
Michael Myers
+3  A: 

Multiply you number by 2^n, convert to an BigInteger, convert to binary String, add a decimal point at position n (from right to left).

Example (quick & ++dirty):

private static String convert(double number) {
    int n = 10;  // constant?
    BigDecimal bd = new BigDecimal(number);
    BigDecimal mult = new BigDecimal(2).pow(n);
    bd = bd.multiply(mult);
    BigInteger bi = bd.toBigInteger();
    StringBuilder str = new StringBuilder(bi.toString(2));
    while (str.length() < n+1) {  // +1 for leading zero
        str.insert(0, "0");
    }
    str.insert(str.length()-n, ".");
    return str.toString();
}
Carlos Heuberger
A: 

Do you want to convert the decimal string to floating-point binary or to a binary string? If the former, just use valueOf(); if the latter, use valueOf() followed by toString() or printf().

Rick Regan