php:ip2long返回负值 [英] php: ip2long returning negative val

查看:109
本文介绍了php:ip2long返回负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function ip_address_to_number($IPaddress) { 
     if(!$IPaddress) {
      return false;
     } else {
      $ips = split('\.',$IPaddress);
      return($ips[3] + $ips[2]*256 + $ips[1]*65536 + $ips[0]*16777216);
     }
}

该函数执行与php捆绑函数相同的代码ip2long。但是,当我打印这2个值时,我得到2个不同的回报。为什么? (我在wamp环境下使用php 5.2.10。)

that function executes the same code as the php bundled function ip2long. however, when i print these 2 values, i get 2 different returns. why? (im using php 5.2.10 on a wamp environment).

ip2long('200.117.248.17'); //returns **-931792879**

ip_address_to_number('200.117.248.17'); // returns **3363174417**

应用并继续:
根据我的IP显示我的国家,优化了mysql

推荐答案


glopes@nebm:~$ php -r "printf('%u', -931792879);"
3363174417

你走了。我的猜测是你在一个32位整数的系统上你的 ip_address_to_number 实际上正在返回一个浮点数。

There you go. My guess is that you are on a system with 32-bit ints and your ip_address_to_number is actually returning a float.

你看,使用32位整数,你的最大正整数是(2 ^ 31) - 1 = 2 147 483 647 ,所以整数包围。

You see, with 32-bit ints, your maximum positive integer is (2^31) - 1 = 2 147 483 647, so the integer wraps around.

如果你想模仿PHP函数的行为,请执行:

If you want to mimic the behaviour of the PHP function, do:

function ip_address_to_number($IPaddress) { 
 if(!$IPaddress) {
  return false;
 } else {
  $ips = split('\.',$IPaddress);
  return($ips[3] | $ips[2] << 8 | $ips[1] << 16 | $ips[0] << 24);
 }
}

(顺便说一下,拆分已弃用)

(by the way, split has been deprecated)

这篇关于php:ip2long返回负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆