title: Flipping bits in python
body: <p>Given an integer n , i want to toggle all bits in the binary representation of that number in the range say lower to upper.
  To do this i do the following [bit_string is a string containing 1's and 0's and is a binary representation of n]</p>
  
  <pre><code>for i in range(lower,upper+1):
     n ^= (1 &lt;&lt; len(bit_string)-1-i) #Toggle the ith bit
  </code></pre>
  
  <p>Then , i also need to determine that given a range, say lower to upper,how many bits are set.My code to do that is as follows :</p>
  
  <pre><code>number_of_ones = 0
  for i in range(lower,upper+1):
      if(n &amp; (1 &lt;&lt; len(bit_string)-1-i)): #Check the ith bit
        number_of_ones+=1
  </code></pre>
  
  <p>But, if n is very large, i think these algorithms would be slow. Is there a way to make these two operations faster/more efficient ?</p>
  
  <p>Thank You</p>