title: Getting the number of leading 1 bits
body: <p>Given an unsigned number, what is a good (preferably fast) way of getting the number of leading 1-bits?</p>
  
  <p>I need this to calculate the CIDR number from a quad-dotted IPv4 netmask.</p>
  
  <p>Note: I have seen <a href="https://stackoverflow.com/questions/2380728/getting-the-number-of-trailing-1-bits">getting-the-number-of-trailing-1-bits</a>, so I can do the table-based lookup.</p>
  
  <p>Note 2: Even though I added a couple of language tags, for me it is about the algorithm, so if you have a good one in another language, please feel free to post.</p>
  
  <p><strong>Edit:</strong> on <a href="http://en.wikipedia.org/wiki/Endianness#Endianness_and_hardware" rel="nofollow noreferrer">endian-ness</a>.</p>
  
  <p>I just found out that the <a href="http://msdn.microsoft.com/en-us/library/ms738563.aspx" rel="nofollow noreferrer">INET_ADDR function</a> and <a href="http://msdn.microsoft.com/en-us/library/ms738571.aspx" rel="nofollow noreferrer">IN_ADDR structure</a> store the IPv4 address in big-endian form, whereas the x86 is little-endian, and most of the processors I use are little-endian too.<br>
  So, lookup tables for this specific case are fast enough.<br>
  But thanks for the other answers: they work very nicely in the more common case.</p>
  
  <p>--jeroen</p>