How to convert a number to binary?

mensanator at aol.com mensanator at aol.com
Thu May 17 19:56:57 EDT 2007


On May 17, 6:45 pm, Lyosha <lyos... at gmail.com> wrote:
> 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)-

Get the gmpy module (note inconsistencies involving octal and hex):

>>> import gmpy
>>> for base in xrange(2,37): print gmpy.digits(255,base)

11111111
100110
3333
2010
1103
513
0377
313
255
212
193
168
143
120
0xff
f0
e3
d8
cf
c3
bd
b2
af
a5
9l
9c
93
8n
8f
87
7v
7o
7h
7a
73




More information about the Python-list mailing list