[Tutor] Integer to binary

Alan Gauld alan.gauld at btinternet.com
Tue Jul 10 19:12:10 CEST 2007


"Mihai Iacob" <aymchaos at yahoo.com> wrote

> Is there a function that converts from integer to
> binary (or a module that handles this)?

Remember that integers are binary. Thats how they are stored.
What I think you want is something that will represent an 
integer as a string of 1s and 0s. Something like the hex 
function which returns the hex string version of a number?

Sadly, and I don't understand why, it doesn't exist in the 
standard library. But its easy to build your own. Here is 
one, Dick has provided another more general form:

def bin(n):
    digits = ['000','001','010','011','100','101','110','111']
    num = oct(int(n))
    result = ""
    for d in num:
        result += digits[int(d)]
    return result.lstrip('0')

NB There's a bug in handling negative numbers!
    
HTH,

Alan G.



More information about the Tutor mailing list