Converting integer to binary representation

Mark Dufour m.dufour at student.tudelft.nl
Tue Dec 16 16:29:50 CET 2003

```On Tuesday 16 December 2003 15:48, Fredrik Lundh wrote:
> "Mark Dufour" <m.dufour at student.tudelft.nl> wrote:
> > I need to convert an integer into some binary representation. I found the
> > following code in the online cookbook (adapted to return a list):
> >
> > binary = lambda n: n>0 and [n&1]+binary(n>>1) or []
> >
> > This is sure nice, but I'm wondering why something like this doesn't seem
> > to be in the standard library, for example by formatting with '%b' %
> > number. I can't think of a any reason for not doing it this way, as
> > working with binary representations is quite common in programming,
>
> really?  what kind of programs are you writing?

I want to loop over the binary representation of numbers, for use in some
algorithm dealing with prime numbers. Of course, there are multiple ways of
doing this, but I like the clean: 'for power, bit in
enumerate(binary(number))', possible with the above code.

> (in my experience, binary numbers only appear in programming text
> books.   humans tend to use decimal numbers, and programmers use
> octal or hexadecimal numbers when they need to "access the bits").

I've seen several attempts on the web for implementing this functionality in
Python, so I guess I'm not the only one needing or wanting it.. ;-) Some
programmers actually do work a lot with bits and prefer binary representation
sometimes, so why not add a simple provision to the language? Like, int()
takes a base argument, why not have str() take one as well?? If only just for
consistency :-)

Mark Dufour.
--
"The employment agency has selected an immature and unproven software package
and its functionality is at the best close to Office 97," said Microsoft
representatives.

```