<?php
/ Sanity checking /
if (empty($input))
die('You must provide an IP-address in the input-variable');
if (preg_match('|[\d.]|',$input)) // only digits and dots
die("'$input' is not a valid IPv4 address");
$parts=explode('.',$input);
if (sizeof($parts)!=4)
die('Only IPv4 addresses are supported');
// Take each of the four address parts and
// transform it into an 8-digit binary value.
$binary='';
foreach($parts as $part)
{
$binary.=str_pad(
decbin($part),
8,
'0',
STR_PAD_LEFT
);
}
/
This hack is used because PHP's bindec() function
is limited to 31-bit values :-(
The BCMath extension and the up-coming gmp extension should
provide methods to deal with infinite precision values.
/
$reverse_binary=strrev($binary);
$decimal=0;
for($i=0;$i<32;$i++)
{
$exp=pow(2,$i);
$decimal+=$exp * intval($reverse_binary[$i]);
}
print "<p>Input: '$input'
<br>Binary: '$binary'
<br>Decimal: $decimal</p>";
?>