简体   繁体   中英

PHP: Converting big integer from string to int with overflow

PHP does not support unsigned ints. Is there a way to convert a string representation of an unsigned integer into a signed integer with overflow?

Example:
On a 32 bit system, PHP can store int values <= 2147483647. I want a way to convert the string "2147483648" to integer, causing it to overflow to -2147483648 instead of being reduced to 2147483647.

Why do I want to do this?
I store IPv4 addresses in a database as unsigned int (32 bits). I want to do binary operations on the addresses in PHP to check for subnets. This needs to be done on every request, so it needs to be quick. Therefore it seems better to store the IP address as an unsigned int rather than storing a string which will have to be converted back and forth.

here is the workaround.

<?php
    $unsignedString = "3000000000";
    echo "unsigned string: ".$unsignedString."<br />";
    $signedInt = intval(doubleval($unsignedString));
    echo "signed int: ".$signedInt."<br />";
?>

The fastest and easiest way to do this is to get your RDBMS to do it somehow.

You can find out what the size of an integer is in PHP by checking the value of the predefined constant PHP_INT_SIZE . This will be 4 if running on a 32-bit system, 8 if running on a 64-bit system.

I suggest that you populate a variable with for example

$smallIntegers = intval(PHP_INT_SIZE == 4);

and then in your query use something like this:

SELECT
    ...,
    CASE
        WHEN :smallIntegers: = 1 AND IPAddress > 2147483647 THEN IPAddress - 4294967296
        ELSE IPAddress
    END AS IPAddress,
    ...
...

您是否可以将IP地址存储在整数数组中,将IP的一部分存储到数组的每个部分,以便将最大值存储为255并存储在任何整数中:

$ipAddress = array(127, 0, 0, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM