[Tutor] How to convert an integer into a binary?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 8 Aug 2001 00:13:39 -0700 (PDT)

```On Wed, 8 Aug 2001, Haiyang wrote:

> How can I convert an interger into a binary code in Python?

Good question!  By the way, going the other way around, from binary to an
integer, is very easy:

###
>>> int('111001', 2)
57
###

and might be useful later on.

[This message does NOT have an "answer" attached to it, but it gives hints
on one way to do the int->binary conversion.]

One thing to notice is that if a number is odd, then its binary (base-2)
representation will end with a '1'.  Here are a few examples:

###
>>> int('10101', 2)
21                    # is odd
>>> int('1010', 2)
10                    # is even
>>> int('101', 2)
5                     # is odd
>>> int('10', 2)
2                     # is even
>>> int('1', 2)
1
###

So if you have some number, then it's really easy to know about the last
digit: just check to see if the number's even or odd.  Knowing what the
rest of the digits look like might still be a mystery though.

The second thing that might be useful is to look again at the example
above, but this time staring at two things: the binary number itself, and
its integer equivalent:

integer    binary
-------    ------
21     10101
10      1010
5        101
2         10
1          1

Take a look at it, and see if you can spot a pattern.  Here's another
interpreter example with a peculiar pattern:

###
>>> int('100110', 2)
38
>>> int('10011', 2)
19
>>> int('1001', 2)
9
>>> int('100', 2)
4
>>> int('10', 2)
2
>>> int('1', 2)
1
###

Forgive me: I'm being deliberately obscure here.  *grin* If you're