Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting binary string into float

Tags:

python

I have an object that I am storing bits in.

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

Is there anyway I can convert the bits into a float? Thanks.

like image 292
nickles Avatar asked Sep 13 '11 01:09

nickles


1 Answers

Here is a solution that works. as_float32 could be extended to as_float64 by replacing "I" with "L" and "f" with "d". See the struct documentation for an explanation.

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
like image 179
Carl F. Avatar answered Sep 30 '22 10:09

Carl F.