python - 将二进制字符串转换为 float

标签 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()

无论如何我可以将位转换为 float 吗?谢谢。

最佳答案

这是一个可行的解决方案。 as_float32 可以扩展为 as_float64,方法是将“I”替换为“L”,将“f”替换为“d”。查看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

关于python - 将二进制字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7395806/

相关文章:

python - 如何在python中将一串小时和分钟转换为分钟?

Python 类范围规则

try 中的 pythonic 返回

python - 使用 Python 读取 UTF8 CSV 文件

Python 如何从 sys.stdin.readline() 中删除换行符

javascript - 在网页(不是本地主机)上实时显示图片(位于计算机上)

Python导入错误: DLL load failed: The specified module could not be found on fman build system (fbs)

python - python可以找出最新的目录吗?

python - 对于一个键值,计算字典列表中其他键值的出现次数

python - 你能在 Python 中创建多个 "if"条件吗?