Welcome, guest | Sign In | My Account | Store | Cart

Unlike bin() function of Python, it can convert floating-point numbers also.

Python, 31 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# dec2bin.py
# FB - 201012057
import math

def dec2bin(f):
    if f >= 1:
        g = int(math.log(f, 2))
    else:
        g = -1
    h = g + 1
    ig = math.pow(2, g)
    st = ""    
    while f > 0 or ig >= 1: 
        if f < 1:
            if len(st[h:]) >= 10: # 10 fractional digits max
                   break
        if f >= ig:
            st += "1"
            f -= ig
        else:
            st += "0"
        ig /= 2
    st = st[:h] + "." + st[h:]
    return st

# MAIN
while True:
    f = float(raw_input("Enter decimal number >0: "))
    if f <= 0: break
    print "Binary #: ", dec2bin(f)
    print "bin(int(f)): ", bin(int(f)) # for comparison

2 comments

Pepe Aracil 13 years, 4 months ago  # | flag

dec2bin for integers only and python < 2.6

def dec2bin(i): s = "" while i: if i & 1: s = "1" + s else: s = "0" + s i = (i >> 1) return s

Pepe Aracil 13 years, 4 months ago  # | flag
# bin(i) for integers only and python < 2.6 

def bin(i):
    s = ""
    while i:
        if i & 1:
            s = "1" + s
        else:
            s = "0" + s
        i = (i >> 1)
    return s
Created by FB36 on Sun, 5 Dec 2010 (MIT)
Python recipes (4591)
FB36's recipes (148)

Required Modules

  • (none specified)

Other Information and Tasks