title: Fastest way to find powers of two higher than a number
body: <p>I am trying to find a very fast way to find the next higher powers of 2 than a very large number (1,000,000) digits. Example, i have 1009, and want to find it's next higher powers of two which is 1024 or 2**10 </p>
  
  <p>I tried using a loop, but for large numbers this is very, very slow</p>
  
  <pre><code>y=0
  while (1&lt;&lt;y)&lt;1009:
     y+=1
  print(1&lt;&lt;y)
  1024
  </code></pre>
  
  <p>While this works, it's slow for numbers larger than a million digits. Is there a faster algorithm to find the next higher powers of 2 than a number that is large?</p>
  
  <p>ANSWERED BY @JonClements  </p>
  
  <p>using 2**number.bit_length() works perfectly. So this will work for large numbers as well. Thanks Jon.</p>
  
  <p>Here's a code example from Jon's implementation:</p>
  
  <pre><code>2**j.bit_length() 
  1024
  </code></pre>
  
  <p>Here's a code example using the shift operator</p>
  
  <pre><code>2&lt;&lt;(j.bit_length()-1) 
  1024
  </code></pre>
  
  <p>Here is the time difference using the million length number, the shift operator and bit_length is significantly faster:</p>
  
  <pre><code>len(str(aa))
  1000000
  
  def useBITLENGTHwithshiftoperator(hm):
    return 1&lt;&lt;hm.bit_length()-1&lt;&lt;1
  
  def useBITLENGTHwithpowersoperator(hm):
    return 2**hm.bit_length()
  
  start = time.time() 
  l=useBITLENGTHwithpowersoperator(aa) 
  end = time.time() 
  print(end - start)                                                                                                                                 
  0.014303922653198242                                                                                                                                             
  
  start = time.time() 
  l=useBITLENGTHwithshiftoperator(aa) 
  end = time.time() 
  print(end - start)                                                                                                                                 
  0.0002968311309814453
  </code></pre>