"Unpack requires a string argument of length 4" when unpacking floats?

css-float, hex, python

Solution

You need four bytes to unpack, so prepend null bytes if necessary:

z = x.decode('hex') 
z = '\0' * (4 - len(z)) + z

Normally `str.decode` only 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:

>>> z = '615885'.decode("hex")
>>> z = '\0' * (4 - len(z)) + z
>>> struct.unpack('!f', z)
(8.939797951825212e-39,)

If you're going to do doubles as well this solution still works, just change `4` to `8`.

Problem

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.

Original source