Count bit count in float in java

This is an interview question: how to count bits in a float in Java? I think I do not have to know the bit representation of the float in order to answer this question. Can I somehow convert a float to an array of bytes? I can use Java serialization, but it seems like overkill.

+3
source share
3 answers

The Float class has:

    public static int floatToIntBits(float value)

which returns a representation of the specified floating point value in accordance with the IEEE 754 single format floating point bit format.

So, you can get a bit using this method, and then count which ones are set.

http://download.oracle.com/javase/7/docs/api/

+5
source

You can use:

Integer.bitCount(Float.floatToIntBits(value))

, ...... , Java API, , . , - , , , , API.

+2

Just like the Java API methods, various bit hacks are hiding here that you could use, although how well they translated into a Java world that I don’t know (or for those who do this, are they more effective when called API). See the "Accounting bits" section.

+1
source

All Articles