简体   繁体   English

如何在Java中将小数转换为二进制?

[英]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). 我需要将以10为基数的0.5转换为以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. 它返回4602678819172646912 ,我猜是十六进制的,但是对我来说这没有意义。

No. 4602678819172646912 is in dec, hex is 0x3fe0000000000000. No.4602678819172646912是dec,十六进制是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). s是符号位,指数是移位2 ^ 9的指数(因此该指数表示-1),尾数是数字1.xxx的xxx部分(暗含1.)。 Therefore, this number is 1.000...*2^-1, which is 0.5. 因此,此数字为1.000 ... * 2 ^ -1,即0.5。

Note that this describes the "normal" numbers only, so no zeros, denormals, NaNs or infinities 请注意,这仅描述了“正常”数字,因此没有零,非正规,NaN或无穷大

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). 将您的数字乘以2 ^ n,转换为BigInteger,转换为二进制 String,在位置n(从右到左)添加一个小数点。

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 . 这是0x3FE0_0000_0000_0000十进制。 The mantissa is the list of zeros after 3FE (which codes sign and exponent). 尾数是3FE之后的零列表(编码符号和指数)。 This is what you are looking for, given that 0.1 before the zeros is implicit. 考虑到零之前的0.1是隐式的,这就是您要寻找的。

Do you want to convert the decimal string to floating-point binary or to a binary string? 您要将十进制字符串转换为浮点二进制还是二进制字符串? If the former, just use valueOf(); 如果是前者,则只需使用valueOf();即可。 if the latter, use valueOf() followed by toString() or printf(). 如果是后者,请使用valueOf(),然后使用toString()或printf()。

0.1 is NOT a binary representation of 0.5 0.1不是0.5的二进制表示

Java will represent 0.5 using IEEE 754, as specified on the Java Language Specification . Java将使用Java语言规范中指定的IEEE 754来表示0.5。 BigInteger.valueOf(Double.doubleToRawLongBits(0.5)).toByteArray() will give you a byte per byte representation of 0.5 as Java does internally. BigInteger.valueOf(Double.doubleToRawLongBits(0.5)).toByteArray()将为您提供0.5的字节/字节表示,就像Java在内部所做的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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