Search code examples
pythontwos-complement

How to convert between floats and decimal twos complement numbers in Python?


I want to convert decimal float numbers in python into twos complement decimal binary numbers. For example 1.5 in twos complement decimal 2.6 (8 bits) would be 0b011000.

Is there a module that can do this for me?


Solution

  • Well, I couldnt find anything so I wrote some code and tested it.Should work...

    def floatToTwosComplementDecimal(intBits,decBits,number):
        if decBits == 0:
            mx = pow(2,intBits-1) - 1 # maximum number
        else:
            mx = pow(2,intBits-1) - pow(2,-1*decBits) # maximum number
        mn = -1*pow(2,intBits-1) # minimum number
        if number > mx:
            print "number:" + str(number) + " has been truncated to: " + str(mx)
            number = mx
        elif number < mn:
            print "number:" + str(number) + " has been truncated to: " + str(mn)
            number = mn
        n = []
        m = 0
        if number < 0:
            n.append(1)
            m = -1*pow(2,intBits-1)
        else:
            n.append(0)
            m = 0
        for i in reversed(range(intBits-1)):
            m1 = m + pow(2,i)
            if number < m1:
                n.append(0)
            else:
                n.append(1)
                m = m1
        for i in range(1,decBits+1):
            m1 = m + pow(2,-1*i)
            if number < m1:
                n.append(0)
            else:
                n.append(1)
                m = m1
        return string.join([str(i) for i in n], '')
    
    def twosComplementDecimalToFloat(intBits,decBits,binString):
        n = 0.0
        if binString[0] == "1":
            n = -1*pow(2,intBits-1)
        for i in range(intBits-1):
            n += int(binString[intBits-1-i])*pow(2,i)
        for i in range(1,decBits+1):
            n += int(binString[intBits-1+i])*pow(2,-1*i)
        return n