How to convert a number to binary?

Lyosha lyoshaM at gmail.com
Thu May 17 19:45:46 EDT 2007


On May 17, 4:40 pm, Michael Bentley <mich... at jedimindworks.com> wrote:
> On May 17, 2007, at 6:33 PM, Lyosha wrote:
>
> > Converting binary to base 10 is easy:
> >>>> int('11111111', 2)
> > 255
>
> > Converting base 10 number to hex or octal is easy:
> >>>> oct(100)
> > '0144'
> >>>> hex(100)
> > '0x64'
>
> > Is there an *easy* way to convert a number to binary?
>
> def to_base(number, base):
>         'converts base 10 integer to another base'
>
>         number = int(number)
>         base = int(base)
>         if base < 2 or base > 36:
>                 raise ValueError, "Base must be between 2 and 36"
>         if not number:
>                 return 0
>
>         symbols = string.digits + string.lowercase[:26]
>         answer = []
>         while number:
>                 number, remainder = divmod(number, base)
>                 answer.append(symbols[remainder])
>         return ''.join(reversed(answer))
>
> Hope this helps,
> Michael

That's way too complicated...  Is there any way to convert it to a one-
liner so that I can remember it?  Mine is quite ugly:
    "".join(str((n/base**i) % base) for i in range(20) if n>=base**i)
[::-1].zfill(1)




More information about the Python-list mailing list