jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Float.floatToIntBits( float ) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Float.floatToIntBits( float )" Watch "Float.floatToIntBits( float )" New topic

Float.floatToIntBits( float )

Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9058
I'm trying to figure out how Float.floatToIntBits( float ) works.

But I'm not seeing the relationship of the output to the input. Seems like there are too many digits (and not enough zeros for
multiples of two).
C:\Java>java Test 1
C:\Java>java Test 2
C:\Java>java Test 4
C:\Java>java Test 8
C:\Java>java Test 16
C:\Java>java Test 32

Can someone explain this?

Also, what would anyone use this for in a practical sense?

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
Hi, Marilyn.
I looked up the code in java.lang.Float; it's a native method, but here are the comments that go along with it:

I also notice that this is the method that java.lang.Float.hashCode() ultimately calls. The hashCode() method represents an object as an int to determine equality of Float objects.
One follow-up question I have, though: In Java, aren't there more floats than ints? And, if so, isn't it possible for two completely different floats to have the same hash code, which could result in all sorts of problems?
Just curious. I hope this helped answer your question, Marilyn.
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9058
Now I see. I forgot to convert the decimal output to its hexadecimal representation. That's where my confusion originated.

floats are only approximations because of their representation in this IEEE 754 floating-point "single precision" bit layout. But I'm sure that the hashing algorithm used is such that the problem you describe is virtually non-existant. It certainly would not be unique to Java if it did. As you noted, it is a native method.

I agree. Here's the link: http://aspose.com/file-tools
subject: Float.floatToIntBits( float )
jQuery in Action, 3rd edition