'convert ipv4 netmask to cidr format

I have the ip and netmask

192.168.1.0 255.255.255.0

I need to convert the netmask into cidr format

192.168.1.0/24

How do I convert ipv4 address and netmask into cidr format?

I am using PHP5.6



Solution 1:[1]

A bit hold the topic, but may help someone else and you have here the solution:

function mask2cidr($mask)
{
  $long = ip2long($mask);
  $base = ip2long('255.255.255.255');
  return 32-log(($long ^ $base)+1,2);

  /* xor-ing will give you the inverse mask,
      log base 2 of that +1 will return the number
      of bits that are off in the mask and subtracting
      from 32 gets you the cidr notation */
}

PHP ip2long help

Solution 2:[2]

The following code transfers the mask to binary to convert the binary to CIDR

    public function mask2cdr($mask) {
          $dq = explode(".",$mask);
          for ($i=0; $i<4 ; $i++) {
             $bin[$i]=str_pad(decbin($dq[$i]), 8, "0", STR_PAD_LEFT);
          }
          $bin = implode("",$bin); 

          return strlen(rtrim($bin,"0"));
    }

Solution 3:[3]

I fixed the code from php ip2long help for 0.0.0.0 mask and simplified it a little (no need to always compute $base = ip2long('255.255.255.255');):

function mask2cidr($mask)
{
    if($mask[0]=='0')
        return 0;

    return 32 - log(~ip2long($mask) + 1, 2);
}

@Barmar's answer is good too, as it will always do the job without any surprises on any PC architecture.

Solution 4:[4]

function convert($ip,$mask){
  return $ip."/".strlen(str_replace("0","",decbin(ip2long($mask))))
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hugo Ferreira
Solution 2 Victor Nuñez
Solution 3 kay27
Solution 4 ????????? ??????????