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

Karthik Gurusamy kar1107 at gmail.com
Tue Jul 17 22:43:38 CEST 2007

```On Jul 17, 5:35 am, Bruno Desthuilliers <bruno.
42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> mosi a écrit :
>
>
>
> > 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?
>
> bruno at bruno:~\$ python
> Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
> [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
>  >>> help(int)
> Help on class int in module __builtin__:
>
> class int(object)
>   |  int(x[, base]) -> integer
>   |
>   |  Convert a string or number to an integer, if possible.  A floating
> point
>   |  argument will be truncated towards zero (this does not include a string
>   |  representation of a floating point number!)  When converting a
> string, use
>   |  the optional base.  It is an error to supply a base when converting a
>   |  non-string. If the argument is outside the integer range a long object
>   |  will be returned instead.
>
>  >>> a = int('100', 2)
>  >>> a
> 4
>  >>>
>
> HTH

While it's interesting to know we can go from binary to int, the OP
wanted the other way.

I think it will be a nice enhancement to add to % operator (like %x,
something for binary, %b or %t say) or something like a.__bin__ as
suggested by the OP.

FWIW, gdb has a /t format to print in binary.

(gdb) p 100
\$28 = 100
(gdb) p /x 100
\$29 = 0x64
(gdb) p /t 100
\$30 = 1100100
(gdb)

--Karthik

```