a=0100; print a ; 64 how to reverse this?
John Machin
sjmachin at lexicon.net
Tue Jul 17 14:02:45 CEST 2007
On Jul 17, 9:09 pm, mosi <skawan... at gmail.com> 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
More information about the Python-list
mailing list