Home > php教程 > php手册 > PHP的ip2long和long2ip函数的实现原理

PHP的ip2long和long2ip函数的实现原理

WBOY
Release: 2016-06-21 08:47:57
Original
1887 people have browsed it

最近要做个十进制数字的可逆转换做邀请码,一直没搞清楚怎么弄的,实在太复杂了,今天弄IP时想到这个可以进行转换,于是研究了下原理:

主要是自己整理了下:


$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);
Copy after login

以上输出的结果为:

203569230
203569230
12.34.56.78
12.34.56.78
Copy after login


这只是实现的一种方法而已,还有其他的办法

我是想用类似的方法,可以直接把一个十进制数字转换为其他十进制数值并可逆,但遇到中间有很多0的数值时发现问题太多了,如 1000100






Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template