如何在PHP上使用64位整数?

nop*_*ole 57 php 64-bit integer

有人知道如何在PHP上使用64位整数吗?它似乎不是由配置文件,而是它可能是一个编译时选项,它取决于平台?

sco*_*tts 75

本机64位整数需要64位硬件和64位版本的PHP.

在32位硬件上:

$ php -r 'echo PHP_INT_MAX;'
2147483647
Run Code Online (Sandbox Code Playgroud)

在64位硬件上:

$ php -r 'echo PHP_INT_MAX;'
9223372036854775807
Run Code Online (Sandbox Code Playgroud)

  • 另外,PHP不能代表UNSIGNED整数.因此,上述数字实际上是2 ^ 63而不是完全可用的无符号整数2 ^ 64. (5认同)
  • 刚刚在64位Windows上测试了最新的PHP 7 RC,看起来他们最终*最终*添加了一致的64位整数支持! (3认同)

tmo*_*ont 53

更新:它现在(在Amd Quad Core,Windows 8.1上测试).

请注意,即使硬件和PHP都是64位,Windows上的PHP根本不支持64位整数.有关详情,请参阅此链接:

在Windows x86_64上,PHP_INT_MAX是2147483647.这是因为在底层的c代码中,long是32位.

但是,x86_64上的linux使用64位长,因此PHP_INT_MAX将为9223372036854775807.

  • "你现在做什么"是什么意思?我看到Windows 64上的PHP 7支持64位整数.是否还有PHP 5.x版本?如果是这样,你从哪里得到它? (3认同)

Mil*_*dev 10

也许你可以使用GMPBCMath扩展.


Jos*_*ren 9

PHP int size与平台有关.有一个名为unpack()的函数,它实质上允许将不同类型的数据从二进制字符串转换为PHP变量.它似乎是存储的唯一方式,因为64位是将它存储为字符串.

我找到了以下代码:http: //www.mysqlperformanceblog.com/2007/03/27/integers-in-php-running-with-scissors-and-portability/

/// portably build 64bit id from 32bit hi and lo parts
function _Make64 ( $hi, $lo )
{

        // on x64, we can just use int
        if ( ((int)4294967296)!=0 )
            return (((int)$hi)<<32) + ((int)$lo);

        // workaround signed/unsigned braindamage on x32
        $hi = sprintf ( "%u", $hi );
        $lo = sprintf ( "%u", $lo );

        // use GMP or bcmath if possible
        if ( function_exists("gmp_mul") )
            return gmp_strval ( gmp_add ( gmp_mul ( $hi, "4294967296" ), $lo ) );

        if ( function_exists("bcmul") )
            return bcadd ( bcmul ( $hi, "4294967296" ), $lo );

        // compute everything manually
        $a = substr ( $hi, 0, -5 );
        $b = substr ( $hi, -5 );
        $ac = $a*42949; // hope that float precision is enough
        $bd = $b*67296;
        $adbc = $a*67296+$b*42949;
        $r4 = substr ( $bd, -5 ) +  + substr ( $lo, -5 );
        $r3 = substr ( $bd, 0, -5 ) + substr ( $adbc, -5 ) + substr ( $lo, 0, -5 );
        $r2 = substr ( $adbc, 0, -5 ) + substr ( $ac, -5 );
        $r1 = substr ( $ac, 0, -5 );
        while ( $r4>100000 ) { $r4-=100000; $r3++; }
        while ( $r3>100000 ) { $r3-=100000; $r2++; }
        while ( $r2>100000 ) { $r2-=100000; $r1++; }

        $r = sprintf ( "%d%05d%05d%05d", $r1, $r2, $r3, $r4 );
        $l = strlen($r);
        $i = 0;
        while ( $r[$i]=="0" && $i<$l-1 )
            $i++;
        return substr ( $r, $i );         
    }

    list(,$a) = unpack ( "N", "\xff\xff\xff\xff" );
    list(,$b) = unpack ( "N", "\xff\xff\xff\xff" );
    $q = _Make64($a,$b);
    var_dump($q);
Run Code Online (Sandbox Code Playgroud)


Ana*_*ski 5

现在你应该得到PHP 7 - 完全一致的64位支持.不仅是整数,还有所有fstat,IO等.Windows上的PHP 7是真正的64位.

  • Clifton,请确保您使用的是 64 位版本。 (2认同)