How to convert base 10 to base 2?

Paul Rubin no.email at nospam.invalid
Tue Aug 21 00:05:45 EDT 2012


Ian Kelly <ian.g.kelly at gmail.com> writes:
> Everybody should know the generic algorithm, though:
> from itertools import chain ...

For n>0, assuming you just want the converted digits and not a string.
String conversion and minus sign for n<0 left as exercise.  Note this
returns a generator that you can convert to a list with list(...).

    def convert(n, base):
        a,b = divmod(n,base)
        if a > 0:
           for e in convert(a,base):
                 yield e
        yield b



More information about the Python-list mailing list