python struct "unpack requires a bytes object of length 8" while converting binay to float
<p>I'm currently trying to transform binaries into floats and viceversa using the struct module. My function works with certain values, like 2.0 or 14.0, but it doesn't with values like 1.0.</p>

<p>I took the code from another question, and changed it from python2 to python3. </p>

<pre><code>import struct

def bin_to_float(b):
    """ convert binary string to float """
    bf = int_to_bytes(int(b, 2), 8)  # 8 bytes needed for IEEE 754 binary64
    bf = bytes(bf, 'UTF-8')
    print(bf)
    return struct.unpack('&lt;d', bf)[0]

def int_to_bytes(n, minlen):  # helper function
    """ int/long to byte string """
    nbits = n.bit_length() + (1 if n &lt; 0 else 0)  # plus one for any sign bit
    nbytes = (nbits+7)//8  # number of whole bytes
    bytes = []
    for i in range(nbytes):
        bytes.append(chr(n &amp; 0xff))
        n &gt;&gt;= 8   
    # zero pad if needed
    if minlen &gt; 0 and len(bytes) &lt; minlen:
        bytes.extend((minlen-len(bytes)) * '0')
    bytes.reverse()  # put high bytes at beginning
    return ''.join(bytes)

# tests

def float_to_bin(f):
    """ convert float to binary string """
    ba = struct.pack('&gt;d', f)
    s = ''.join('{:08b}'.format(b) for b in ba)
    # strip off leading zeros
    for i in range(len(s)):
        if s[i] != '0':
             break
    else:  # all zeros
        s = '0'
        i = 0
    return s[i:]

import math

floats = [2.0, 1.0, -14.0, 12.546, math.pi]


for f in floats:
    binary = float_to_bin(f)
    print ('float_to_bin(%f): %r' % (f, binary))
    float = bin_to_float(binary)
    print ('bin_to_float(%r): %f' % (binary, float))
    print ()
</code></pre>

<p>The problem seems to be that when I encode the str in bytes, I get 9 bytes instead of 8, but this happens only sometimes. This is the console readings:</p>

<pre><code>float_to_bin(2.000000): '100000000000000000000000000000000000000000000000000000000000000'
b'@\x00\x00\x00\x00\x00\x00\x00'
bin_to_float('100000000000000000000000000000000000000000000000000000000000000'): 0.000000

float_to_bin(1.000000): '11111111110000000000000000000000000000000000000000000000000000'
b'?\xc3\xb0\x00\x00\x00\x00\x00\x00'
Traceback (most recent call last):
  File "C:/Users/arzuffi pc test/Desktop/prova struct.py", line 47, in &lt;module&gt;
    float = bin_to_float(binary)
  File "C:/Users/arzuffi pc test/Desktop/prova struct.py", line 8, in bin_to_float
    return struct.unpack('&lt;d', bf)[0]
struct.error: unpack requires a bytes object of length 8
</code></pre>

<p>I can't seem to figure out why this happens and how to prevent it from happening :/</p>

<p>Does anybody knows why this is?</p>

<p>Thank you very much in advance.</p>

<p>EDIT: J.J. Hakala answered brilliantly, so I'll post the answer up here:</p>

<pre><code>import struct

def bin_to_float(b):
    """ convert binary string to float """
    return struct.unpack('&lt;d', struct.pack('&lt;Q', int(b, 2)))[0]

def float_to_bin(f):
    """ convert float to binary string """
    return '{:b}'.format(struct.unpack('&lt;Q', struct.pack('&lt;d', f))[0])
</code></pre>

<p>If someone wants to do the same with 32 bits float, this should be good:</p>

<pre><code>import struct

def bin_to_float(b):
    """ convert binary string to float """
    return struct.unpack('&lt;f', struct.pack('&lt;L', int(b, 2)))[0]
def float_to_bin(f):
    """ convert float to binary string """
    return '{:b}'.format(struct.unpack('&lt;L', struct.pack('&lt;f',f))[0])
</code></pre>

<p>Thank you very much everybody!!!</p>