title: Base-2 (Binary) Representation Using Python
body: <p>Building on <a href="https://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python#13107">How Do You Express Binary Literals in Python</a>, I was thinking about sensible, intuitive ways to do that Programming 101 chestnut of displaying integers in base-2 form.  This is the best I came up with, but I'd like to replace it with a better algorithm, or at least one that should have screaming-fast performance.  </p>
  
  <pre><code>def num_bin(N, places=8):
      def bit_at_p(N, p):
          ''' find the bit at place p for number n '''
          two_p = 1 &lt;&lt; p   # 2 ^ p, using bitshift, will have exactly one
                           # bit set, at place p
          x = N &amp; two_p    # binary composition, will be one where *both* numbers
                           # have a 1 at that bit.  this can only happen 
                           # at position p.  will yield  two_p if  N has a 1 at 
                           # bit p
          return int(x &gt; 0)
  
      bits =  ( bit_at_p(N,x) for x in xrange(places))
      return "".join( (str(x) for x in bits) )
  
      # or, more consisely 
      # return "".join([str(int((N &amp; 1 &lt;&lt; x)&gt;0)) for x in xrange(places)])
  </code></pre>