Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned int to signed in php

It appears, that in 32bit OS ip2long returns signed int, and in 64bit OS unsigned int is returned.

My application is working on 10 servers, and some are 32bit and some are 64bit, so I need all them to work same way.

In PHP documentation there is a trick to make that result always unsigned, but since I got my database already full of data, I want to have it signed.

So how to change an unsigned int into a signed one in PHP?

like image 468
Thinker Avatar asked May 16 '09 13:05

Thinker


1 Answers

PHP does not support unsigned integers as a type, but what you can do is simply turn the result of ip2long into an unsigned int string by having sprintf interpret the value as unsigned with %u:

 $ip="128.1.2.3";
 $signed=ip2long($ip);             // -2147417597 in this example
 $unsigned=sprintf("%u", $signed); //  2147549699 in this example

Edit, since you really wanted it to be signed even on 64 bit systems - here's how you'd convert the 64 bit +ve value to a 32 bit signed equivalent:

$ip = ip2long($ip);
if (PHP_INT_SIZE == 8)
{
    if ($ip>0x7FFFFFFF)
    {
        $ip-=0x100000000;
    }
}
like image 194
Paul Dixon Avatar answered Sep 18 '22 02:09

Paul Dixon