note 105083 deleted from function.ip2long by danbrown

From: Date: Tue, 26 Jul 2011 21:42:17 +0000
Subject: note 105083 deleted from function.ip2long by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181923@lists.php.net to get a copy of this message
Note Submitter: contact at nullivex dot com ---- This is an improvement on an existing function submitted on this list which I have added below. Improved function --------- <?php //with static magic number function mask2cidr($mask){ return 32 - intval(log(4294967296 - ip2long($mask),2)); } //with bit shifted net size function mask2cidr($mask){ return 32 - intval(log((1<<32) - ip2long($mask),2)); } //constant define('MAX_NETSIZE',4294967296); function mask2cidr($mask){ return 32 - intval(log(MAX_NETSIZE - ip2long($mask),2)); } /* Preferred method is a constant with a magic number. Using the least amount of memory and CPU cycles along with greatest readability. --- The first two functions work great standalone though. */ ?> Original Method --------------------------------------- A quick method to convert a netmask (ex: 255.255.255.240) to a cidr mask (ex: /28): <?php 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 */ } ?>

« previous php.notes (#181923) next »