title: How to calculate prefix length for given IPv4 network mask?
body: <p>I need to calculate the prefix length of a IPv4 network mask. My first naive approach is</p>
  
  <pre><code>int calculate_prefix_length (uint32_t address) {
    int set_bits;
      for (set_bits = 0; address; address &gt;&gt;= 1) {
        set_bits += address &amp; 1;
      }
    return set_bits;
  }
  </code></pre>
  
  <p>This is probably not very fast. is there a better solution?</p>