I am trying to convert hex value to float using (Python 2.7) the following method:
def hex2float(x):
y = 0
z = x.decode('hex')
try:
y = struct.unpack('!f', z)[0]
except:
print sys.exc_info()[1]
print 'z = ' + z
print 'y = %s' % (y)
print 'x = ' + x
return
def foo28():
x = '615885' #8.9398e-039
hex2float(x)
The output is as follows:
unpack requires a string argument of length 4
z = aXà
y = 0
x = 615885
I notice that I get the exception message for really small values. Is there a proper way to convert hex values to floating values for such cases.
You need four bytes to unpack, so prepend null bytes if necessary:
Normally
str.decodeonly outputs as much bytes as necessary to represent the value, so that’s why you only see it happen for small values.This works perfectly:
If you’re going to do doubles as well this solution still works, just change
4to8.