简体   繁体   中英

PHP var becoming negative

I have this code :

<?php
$integer = 33963677451;
$integer &= 0xFFFFFFFF;
echo $integer;
?>

But, when I execute it, the output is

-396060917

The same function in Python

if __name__ == '__main__':
    integer = 33963677451
    integer &= 0xFFFFFFFF
    print integer

The output is

3898906379

It seems PHP can't store big variables. Do you guys have any idea how to get the same result in PHP I have in Python ?

Thanks !

That value is too big for an integer, python dynamically casts that into a long variable. INT_MAX defines how big your integer can be before it switches over into a double. If you want to manipulate large numbers without quirks use GMPLIB a multiple precision arithmetic library.

Your 33,963,677,451 is above what a signed 32bit integer supports (max 2,147,483,647). 64bit PHP versions do support higher values.

php only supports signed integers. You are seeing overflow

also, the answer for the python case should be 33963677451

I don't know if it's just a typo, but you are using different values when performing the AND operation in each language. :)

You have "0xFFFFFFFFFFF" (11 chars) in your PHP version, as opposed to only 8 in the Python version.

Either way, it should be integer overflow.

<?php
$integer = (float) 33963677451;
$integer &= 0xFFFFFFFFFFF;
echo $integer;

try making sure that $integer is of type float.

for more: http://www.php.net/manual/de/language.types.integer.php#language.types.integer.overflow

If you wish to see whats happening, here is a printf statement showing the different types.

$i1 = 33963677451;
$i2 = 0xFFFFFFFFFFF;
printf("%b (%d, %f) & \n%b (%d, %f)\n = \n%b (%d, %f)", 
        $i1, $i1, $i1, $i2, $i2, $i2, $i1&$i2, $i1&$i2, $i1&$i2);

PHP casts integers larger than 32 bits to floats. It seems that you can not perform this operation on floats.

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