Home  >  Article  >  Backend Development  >  Implementation principle of PHP's ip2long and long2ip functions_PHP tutorial

Implementation principle of PHP's ip2long and long2ip functions_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:26:58867browse

I recently wanted to make a reversible conversion of decimal numbers to use as an invitation code. I have never figured out how to do it. It is too complicated. When I was working on IP today, I thought that this could be converted, so I studied the principle:

Mainly organized by myself:


$ip = '12.34.56.78';
$ips = explode('.', $ip);
$result = 0;
$result += $ips[0]<<24;
$result += $ips[1]<<16;
$result += $ips[2]<<8;
$result += $ips[3];
echo bindec(decbin($result));
echo &#39;<br>&#39;;
echo bindec(decbin(ip2long($ip)));
echo &#39;<br>&#39;;

$str = &#39;&#39;;
$str .= intval($result/intval(pow(2, 24))) .&#39;.&#39;;
$str .= intval(($result&0x00FFFFFF)/intval(pow(2, 16))) .&#39;.&#39;;
$str .= intval(($result&0x0000FFFF)/intval(pow(2, 8))) .&#39;.&#39;;
$str .= intval($result&0x000000FF);

echo $str;
echo &#39;<br>&#39;;
echo long2ip($result);

The result of the above output is:

203569230
203569230
12.34.56.78
12.34.56.78


This is just one way to achieve it, there are other ways

I wanted to use a similar method, which can directly convert a decimal number into other decimal values ​​and reversibly, but I found too many problems when encountering values ​​with many 0s in the middle, such as 1000100




www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/820633.htmlTechArticleI recently wanted to make a reversible conversion of decimal numbers into an invitation code. I haven’t figured out how to do it. It’s too complicated. Yes, when I was getting the IP today, I thought that this could be converted, so I studied the original...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn