How to convert float number to Binary?

前端 未结 6 807
不思量自难忘°
不思量自难忘° 2020-12-07 16:53

Can anyone please tell me how can I convert this float number: 12.25 to binary? I know how to convert the \"12\" but not the 0.25

Any help is much appreciated. Thank

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 17:14

    x = float(raw_input("enter number between 0 and 1: "))
    
    p = 0
    while ((2**p)*x) %1 != 0:
        p += 1
        # print p
    
        num = int (x * (2 ** p))
        # print num
    
        result = ''
        if num == 0:
            result = '0'
        while num > 0:
            result = str(num%2) + result
            num = num / 2
    
        for i in range (p - len(result)):
            result = '0' + result
        result = result[0:-p] + '.' + result[-p:]
    
    print result #this will print result for the decimal portion
    

提交回复
热议问题