java 将浮点数转换为位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10643754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:56:47  来源:igfitidea点击:

Convert float to bits

javafloating-pointdouble

提问by Jan Ajan

How can I get single bits (or an entire variable) of a doubleor a float?

如何获得 adouble或 a 的单个位(或整个变量)float

For example if I have float a = 0.5;

例如,如果我有 float a = 0.5;

I would expect a Stringequal to:
"00111111000000000000000000000000"

我希望String等于:
"00111111000000000000000000000000"

or in hex:
"F000000"

或十六进制:
"F000000"

回答by Mike Samuel

long bits = Double.doubleToLongBits(myDouble);
System.out.println(Long.toBinaryString(bits));

回答by user949300

Look at Float.floatToIntBits() or Float.floatToRawIntBits(). That gets you the bits as an int. If you need it as a String, Integer.toBinaryString().

看看 Float.floatToIntBits() or Float.floatToRawIntBits()。这会让你得到一个 int 位。如果你需要它作为一个字符串,Integer.toBinaryString().

Note, there may be an issue if the HSB is on - you may need to convert to a long to avoid an "overflow".

请注意,如果 HSB 开启,则可能会出现问题 - 您可能需要转换为 long 以避免“溢出”。

回答by walrider89

public void printFloatBits(float f) {
    int bits = Float.floatToIntBits(f);
    // Extract each bit from 'bits' and compare it by '0'
    for (int i=31; i>=0; --i) {
        // int mask = 1 << i;
        // int oneBit = bits & mask;
        // oneBit == 0 or 1?
        System.out.print((bits & (1 << i)) == 0 ? "0" : "1");
    }
}

回答by kentcdodds

Double.byteValue()might help you.

Double.byteValue()可能会帮助你。

There is also a 32-bit equivalent Float.byteValue().

还有一个 32 位等效的Float.byteValue().