Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sortable floating point to integer #2834

Open
electrum opened this issue May 31, 2017 · 0 comments
Open

Sortable floating point to integer #2834

electrum opened this issue May 31, 2017 · 0 comments

Comments

@electrum
Copy link

It is often useful to convert a floating point values to integers in a way that preserves ordering. For example, when converting to a sortable binary key for LevelDB, storing in a SQL database that doesn't handle NaN or infinity, etc.

This trick doesn't seem to be well-publicized, but is used by Lucene, etc.

/**
 * Converts a double value to a sortable long. The value is converted by swapping
 * some bits in the IEEE 754 layout to be able to compare the result as a long.
 *
 * @see #sortableLongToDouble(long)
 */
public static long doubleToSortableLong(double value)
{
    long bits = doubleToLongBits(value);
    return bits ^ ((bits >> 63) & Long.MAX_VALUE);
}

/**
 * Converts a sortable long to double.
 *
 * @see #doubleToSortableLong(double)
 */
public static double sortableLongToDouble(long value)
{
    value ^= (value >> 63) & Long.MAX_VALUE;
    return longBitsToDouble(value);
}

/**
 * Converts a float value to a sortable int. The value is converted by swapping
 * some bits in the IEEE 754 layout to be able to compare the result as a int.
 *
 * @see #sortableIntToFloat(int)
 */
public static int floatToSortableInt(float value)
{
    int bits = floatToIntBits(value);
    return bits ^ ((bits >> 31) & Integer.MAX_VALUE);
}

/**
 * Converts a sortable int to float.
 *
 * @see #floatToSortableInt(float)
 */
public static float sortableIntToFloat(int value)
{
    value ^= (value >> 31) & Integer.MAX_VALUE;
    return intBitsToFloat(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants