I’m working in Hadoop, and I need to provide a comparator to sort objects as raw network order byte arrays. This is easy for me to do with integers — I just compare each byte in order. I also need to do this for floats. I think, but I can’t find a reference, that the IEEE 754 format for floats used by Java can be sorted by just comparing each byte as a signed 8 bit value.
Can anyone confirm or refute this?
Edit: the representation is IEEE 754 32 bit floating point. I actually have a (larger) byte buffer and an offset and length within that buffer. I found some utility methods already there that make it easy to turn this into a float, so I guess this question is moot. I’m still curious if anyone knows the answer.
Positive floats have the same ordering as their bit representations viewed as 2s complement integers. Negative floats do not.
For example, the bit representation of -2.0f is
0xc0000000and -1.0f is0xbf800000. If you try to use a comparison on the representations, you get -2.0f > -1.0f, which is incorrect.There’s also the issue of NaNs (which compare unordered against all floating point data, whereas the representations do not), but you may not care about them.