Are Floats' Bit Patterns Ordered?
encoding, floating-point, floating-point-precision, java
Solution
Sorting by bit pattern is sufficient, but not necessary, to sort numerically. (There are signed zeroes and NaNs to harsh your style.)
You can access the bit pattern of a `double` using `Double.doubleToLongBits()` and of a `float` using `Float.floatToIntBits()`.
EDIT: As Mark Dickinson points out, this sorts negative numbers backward. The following transformation gives you something sufficient, but not necessary, to sort numerically:
longbits ^= (longbits >> 63) & 0x7fffffffffffffff;
The effect here is to xor the sign bit with all other bits. This transformation is its own inverse; apply it once before and once after sorting.
Problem
Looking at the IEEE float/double representation ``` [mantissa sign][signed exponent][unsigned mantissa] ``` Am I correct to assume that sorting these values numerically always results in the same as sorting the bit patterns themselves lexicographically? My other question then is how do I obtain the bits (or rather bytes) of the bit pattern (of the IEEE representation) of a float/double in Java? (Or alternatively just on the HotSpot JVM, if the internal representation isn't specified.) How would I construct an IEEE-like representation for arbitrary-precision Decimals (like `java.math.BigDecimal`)?