Thank you, this is great, I thought that this should be standard in python 2.4 or 2.5 or in some standard library (math ???) Didn`t find anything.
On Jul 17, 2:05 pm, John Machin <[EMAIL PROTECTED]> wrote: > On Jul 17, 9:09 pm, mosi <[EMAIL PROTECTED]> wrote: > > > > > Problem: > > how to get binary from integer and vice versa? > > The simplest way I know is: > > a = 0100 > > a > > 64 > > > but: > > a = 100 (I want binary number) > > does not work that way. > > > a.__hex__ exists > > a.__oct__ exists > > > but where is a.__bin__ ??? > > > What`s the simplest way to do this? > > Thank you very much. > > Here's a sketch; I'll leave you to fill in the details -- you may wish > to guard against interesting input like b < 2. > > >>> def anybase(n, b, digits='0123456789abcdef'): > > ... tmp = [] > ... while n: > ... n, d = divmod(n, b) > ... tmp.append(digits[d]) > ... return ''.join(reversed(tmp)) > ...>>> anybase(1234, 10) > '1234' > >>> anybase(7, 2) > '111' > >>> [anybase(64, k) for k in range(2, 17)] > > ['1000000', '2101', '1000', '224', '144', '121', '100', '71', '64', > '59', '54', '4c', '48', '44', '40'] > > > > HTH, > John -- http://mail.python.org/mailman/listinfo/python-list