基于 IEEE 754 标准的 单精度浮点数计算方式 (未完成)

def dec2bin(dec):
    if dec < 0:
        s = '1'
        dec = dec * (-1)
    else:
        s = '0'

    e = 127
    dec = float(dec)
    r = int(str(dec).split('.')[0])
    i = float('0.'+str(dec).split('.')[1])

    rA = []
    if s == '0':

        if r == 0:
            rA = ['0']
        else:
            while r > 0:
                rA.append(r%2)
                r//=2

        rA.reverse()
        rB = ''.join([str(i) for i in rA])
        e = len(str(int(rB))) - 1 + e
    elif s == '1':
        rB = '0'
    # """
    # 0000 1111 0111 0000 1111 0000 1111 0000
    # """


    iNum = 23 - len(str(int(rB))) + 1

    iA = []
    while len(iA) < iNum:
        i *= 2

        if i>= 1:
            iA.append('1')
            i -= 1
            if 
        else:
            iA.append('0')
            if rB == '0' and int(''.join(iA)) <= 0:
                print(iA)
                iNum += 1
                e -= 1

    print(s,bin(e),rB,iA)

def main():
    dec2bin(0.1)
    pass

if __name__ == '__main__':
    main()

参考文献:

[1]. IEEE 754浮点数标准详解

posted @ 2019-04-07 15:51  缘起花渊  阅读(1060)  评论(0编辑  收藏  举报