Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Float.floatToIntBits( float )

 
Marilyn de Queiroz
Sheriff
Posts: 9067
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
1065353216
C:\Java>java Test 2
1073741824
C:\Java>java Test 4
1082130432
C:\Java>java Test 8
1090519040
C:\Java>java Test 16
1098907648
C:\Java>java Test 32
1107296256

Can someone explain this?

Also, what would anyone use this for in a practical sense?
 
Art Metzer
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Art
 
Marilyn de Queiroz
Sheriff
Posts: 9067
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic