Converting integer to binary representation

Harry George harry.g.george at boeing.com
Tue Dec 16 04:19:17 EST 2003


"Fredrik Lundh" <fredrik at pythonware.com> writes:

> "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?
> 
> (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").
> 
> </F>
> 
> 
> 
> 

In my experience, binaries are used in a) hardware, e.g., setting port
values, and b) data format conversions (e.g., IEEE vs EBCDIC floats).
In both cases, an occassional literal shows up in the program, but
more importantly, it helps to see the binaries in debug statements.

Yes, programmers use octal or hex to access bits, but only because
that is what they have available.  Modula-3 has a fine (though
verbose) set of functions for the task which do not require mentally
juggling octal and hex.  


-- 
harry.g.george at boeing.com
6-6M31 Knowledge Management
Phone: (425) 342-5601




More information about the Python-list mailing list