a=0100; print a ; 64 how to reverse this?

Daniel no at no.no
Tue Jul 17 14:17:38 CEST 2007


On Tue, 17 Jul 2007 14:09:35 +0300, mosi <skawanagi 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.
>
Write your own?

something like:

def bin(x):
  from math import log
  bits = (8 if x == 0 else 8*(int(log(x)/log(2))/8+1))
  return ''.join([str((x >> i) & 1) for i in range(bits)[::-1]])

though that's probably slow :/


-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/



More information about the Python-list mailing list