Richard
Richard

Reputation: 15862

convert 2 ints to 32 float which works for all cases

Looking at question Python: convert 2 ints to 32 float it is shown that two intgers can be converted to a floating point number. The solution given was:

from struct import pack, unpack
f = unpack('>f',pack('>HH',i1,i2))[0]

In the comments it was pointed out that this will not work for all cases. I need to integrate a way to convert two integers to floating point for a production piece of code, so all cases will have to be accounted for. Is there a better way to achieve this?

Upvotes: 0

Views: 121

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121296

The caveats in the comments on that answer only apply for the reverse operation.

For all unsigned 16-bit integers i1 and i2, packing to bytes then unpacking as float will work without problems.

If you have the time, you can verify this yourself for all 4294+ million combinations with:

from struct import pack, unpack
for i1, i2 in product(xrange(2**16), repeat=2):
    try:
        f = unpack('>f', pack('>HH', i1, i2))
    except Exception:
        print 'Fails for {}, {}'.format(i1, i2)

Or, just take my word for it.

Upvotes: 1

Related Questions