note 105083 added to function.ip2long

From: Date: Tue, 26 Jul 2011 20:53:46 +0000
Subject: note 105083 added to function.ip2long
Groups: php.notes 
Request: Send a blank email to php-notes+get-181920@lists.php.net to get a copy of this message
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 */ } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 69.65.5.30 ---- Manual Page -- http://www.php.net/manual/en/function.ip2long.php Edit -- https://master.php.net/note/edit/105083 Del: integrated -- https://master.php.net/note/delete/105083/integrated Del: useless -- https://master.php.net/note/delete/105083/useless Del: bad code -- https://master.php.net/note/delete/105083/bad+code Del: spam -- https://master.php.net/note/delete/105083/spam Del: non-english -- https://master.php.net/note/delete/105083/non-english Del: in docs -- https://master.php.net/note/delete/105083/in+docs Del: other reasons-- https://master.php.net/note/delete/105083 Reject -- https://master.php.net/note/reject/105083 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#181920) next »