How to convert float to sortable integer in Python

Carl Banks pavlovevidence at
Wed Jan 17 08:07:49 CET 2007

shellon wrote:
> I'm sorry I mistake the function name, the function is
> floatToRawIntBits(), it convert ieee 754 floating point number to
> integer,  e.g. if f1>f2 then floatToRawBits(f1) > floatToRawBits(f1)

You can get the raw bits of a floating point number by packing into a
string then unpacking it as an integer, but the invariant you give
doesn't hold when you do that.  That is, f1>f2 does not guarantee
rawbits(f1)>rawbits(f2).  So be warned.

Python floats are double-precision internally, so the integer returned
would have to hold at least 64-bits (i.e., it'd be a long on 32-bit

import struct

def double_to_raw_int(d):
    return struct.unpack("=q",struct.pack("=d",d))

> I want convert floating point number to sortable string to index in
> Lucene, so I want first to conver the floating point number to integer
> first, and than convert the integer to sortable string?

I presume that, by "sortable string", you mean a numerical
representation (padded or something), but if all you want is a string
containing the bits of the number, struct.pack("=d",d) will get you an
8-byte string representing the bits without having to change it to an
integer first.  Check the documentation for the struct module if you
need a certain endianness.

> so How to convert a ieee 754 floating point to raw bits like the java
> api floatToRawBits do?

See documentation for the struct module.

Carl Banks

More information about the Python-list mailing list