简体   繁体   中英

How do I convert a decimal fraction to binary in Java?

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.

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

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();
}

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.

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().

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM