问题
I'm looking for a way to serialize floating points so that in their serialized form a lexicographical comparison is the same as a floating point comparison. I think it is possible by storing it in the form:
| signed bit (1 for positive) | exponent | significand |
The exponent and the significand would be serialized as big-endian and the complement would be taken for negative numbers.
Would this work? I don't mind if it breaks for NaN, but having INF comparison working would be nice.
回答1:
The format of IEEE numbers are specifically designed so that "plain" integer comparison could be used. However, this only applies when two numbers of the same sign is compared.
Your suggestion to complement the numbers when they are negative is sound, so this will work.
This will work for +-Inf:s and for subnormal numbers. NaN:s, however, will not work, or rather, they will be considered "larger" than inf:s.
The only problematic case is "-Zero" (i.e. sign=1, exponent=0, and mantissa=0). Accoring to IEEE, Zero == -Zero. You have to decide if you want to emit -Zero as Zero, treat them as different, or add special code to the comparison routine.
来源:https://stackoverflow.com/questions/5243091/floating-point-serialization-lexicographical-comparison-floating-point-compa