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

社会主义新天地 提交于 2019-12-04 19:39:21

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!