Flipping bits in python
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]

  
    for i in range(lower,upper+1):
       n ^= (1 << len(bit_string)-1-i) #Toggle the ith bit

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 :

    number_of_ones = 0
    for i in range(lower,upper+1):
        if(n & (1 << len(bit_string)-1-i)): #Check the ith bit
          number_of_ones+=1

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 ?
    
Thank You
Flipping bits in python
===

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]

  
    for i in range(lower,upper+1):
       n ^= (1 << len(bit_string)-1-i) #Toggle the ith bit

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 :

    number_of_ones = 0
    for i in range(lower,upper+1):
        if(n & (1 << len(bit_string)-1-i)): #Check the ith bit
          number_of_ones+=1

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 ?
    
Thank You