Unsigned int for signing in php

It looks like a ip2longsigned int is returned on a 32-bit OS , and an unsigned int is returned on a 64-bit OS.

My application runs on 10 servers, and some of them are 32 bits, and some of them are 64 bits, so I need them all to work the same.

There is a trick in the PHP documentation to make this result always unsigned, but since I got my database already populated with data, I want it to be signed.

So how to change unsigned int into signed in PHP?

+3
source share
4 answers

PHP , ip2long unsigned int string sprintf unsigned %u:

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

, , 64- - 64 + ve 32- :

$ip = ip2long($ip);
if (PHP_INT_SIZE == 8)
{
    if ($ip>0x7FFFFFFF)
    {
        $ip-=0x100000000;
    }
}
+12

Fwiw, MySQL, , IP- MySQL INET_ATON() ( INSERTING/UPDAT (E) " ing) INET_NTOA() ( SELECT). MySQL - , .

:

SELECT INET_NTOA(ip_column) FROM t;

INSERT INTO t (ip_column) VALUES (INET_ATON('10.0.0.1'));

.

, INET_NTOA()/INET_ATON() MySQL ip2long()/long2ip() PHP, MySQL INT UNSIGNED, PHP . !

+3

int 32 64- :

function signedint32($value) {
    $i = (int)$value;
    if (PHP_INT_SIZE > 4)   // e.g. php 64bit
        if($i & 0x80000000) // is negative
            return $i - 0x100000000;
    return $i;
} 
+2

- , . .


64- PHP5. . 32- int 64- int , :

$ip_int = ip2long($ip);
if (PHP_INT_SIZE == 8) // 64bit native
{
  $temp_int = (int)(0x7FFFFFFF & $ip_int);
  $temp_int |= (int)(0x80000000 & ($ip_int >> 32));
  $ip_int = $temp_int;
}

64- ($ ip_int) , . .

+1
source

Source: https://habr.com/ru/post/1708484/


All Articles