6

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)?

Dexter
  • 3,072
  • 5
  • 31
  • 32
  • 1
    http://meta.stackexchange.com/questions/39223/one-post-with-multiple-questions-or-multiple-posts – NPE May 27 '14 at 23:08
  • Just for starters, negative numbers have a 1 in the high order bit, so they would sort AFTER the positive numbers. – Jim Garrison May 27 '14 at 23:10
  • @JimGarrison: Same happens with signed integer types. – tmyklebu May 27 '14 at 23:12
  • @JimGarrison: So assuming I flip the one bit myself in the bit pattern, is there anything else preventing me from sorting the values by bit-pattern? – Dexter May 27 '14 at 23:15
  • 2
    If the floating point number is negative then you have to flip all the rest of the bits to keep the sorted order. – Louis Wasserman May 28 '14 at 09:40
  • Jesus. No. You don't have to touch anything. Negative numbers sort before positive numbers and that's fine. – tmyklebu May 28 '14 at 16:16
  • 3
    @tmyklebu: If the bits of the float/double are left untouched, and reinterpreted as the bits of a signed two's complement integer of appropriate width, negative numbers will sort in the reverse order to the normal numeric order. E.g., the result of sorting `[1.0, 2.0, -1.0, -2.0]` will be `[-1.0, -2.0, 1.0. 2.0]`. So yes, negative numbers sort before positive numbers, but you don't get the usual numeric ordering this way. – Mark Dickinson May 28 '14 at 20:37
  • @MarkDickinson: Correct. I should update my answer. Pity I can't update my comment. – tmyklebu May 28 '14 at 21:36

1 Answers1

8

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.

tmyklebu
  • 13,915
  • 3
  • 28
  • 57