将二进制字符串转换为float

时间:2011-09-13 01:16:11

标签: python

我有一个对象,我正在存储位。

class Bitset:
    def __init__(self, bitstring):
        self.bitlist = []
        for char in bitstring:
            self.bitlist.append(int(char))

    def flipBit(self, index):
        val = self.bitlist[index]
        val = (val + 1) % 2
        self.bitlist[index] = val
        self.newBitstring()

    def bitstring(self):
        newString = ''
        for val in self.bitlist:
            newString = newString + str(val)
        return newString

    def __len__(self):
        return len(self.bitlist)

    def __str__(self):
        return self.bitstring()

    def __repr__(self):
        return self.bitstring()

无论如何我可以将这些位转换为浮点数吗?感谢。

2 个答案:

答案 0 :(得分:5)

如果您不想重新发明轮子,有些库可以为您完成所有这些。我的bitstring图书馆可以提供帮助:

>>> from bitstring import BitArray
>>> a = BitArray(float=0.34, length=32)
>>> a.bin
'00111110101011100001010001111011'
>>> a.float
0.3400000035762787
>>> a.bin = '01001001011101000010010000000000'
>>> a.float
1000000.0
>>> a.bytes = 'helloall'
>>> a.float
7.819486525216155e+194

只有32位或64位时才允许浮点解释;请查看documentation了解更多详情。

答案 1 :(得分:4)

这是一个有效的解决方案。通过将“I”替换为“L”并将“f”替换为“d”,as_float32可以扩展为as_float64。有关说明,请参阅struct documentation

def as_float32(self):
    """
    See: http://en.wikipedia.org/wiki/IEEE_754-2008
    """
    from struct import pack,unpack
    s = self.bitlist
    return unpack("f",pack("I", bits2int(s)))

# Where the bits2int function converts bits to an integer.  
def bits2int(bits):
    # You may want to change ::-1 if depending on which bit is assumed
    # to be most significant. 
    bits = [int(x) for x in bits[::-1]]

    x = 0
    for i in range(len(bits)):
        x += bits[i]*2**i
    return x