"Unpacking requires a string argument of length 4" when unpacking a float?

I am trying to convert a hexadecimal value to a 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 am getting an exception message for really small values. Is there a way to convert hexadecimal values ​​to floating values ​​for such cases.

+3
source share
1 answer

You need four bytes to decompress, so add zero bytes if necessary:

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

It usually str.decodeoutputs as many bytes as necessary to represent the value, so you see that this only happens with small values.

This works great:

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

, , 4 8.

+8

All Articles