4
   pack('H*', dechex(12345678900)) /* on 32bit */  
!= pack('H*', dechex(12345678900)) /* on 64bit */

为什么 ?

4

1 回答 1

1

我不知道如何解决它,但我想我知道为什么会这样。这里没有错误 - 从手册http://php.net/manual/en/function.dechex.php直接出来

可以转换的最大数字是十进制的 4294967295,结果为“ffffffff”

我不知道“内部”php 到底发生了什么,但您可能会导致 32 位无符号整数溢出(12,345,678,900 > 4,294,967,295)。由于在 64 位上,此限制应为 18,446,744,073,709,551,615,因此 dechex 返回“正确”值(似乎没有记录 32 位与 64 位的差异,而且我可能错了,因为我没有 64 位系统进行测试)。

//编辑:

作为最后的手段,您可以使用GMP扩展为 32 位系统创建自己的 hecdex 函数,但这会产生大量开销。可能会成为现代编程已知的最慢的实现之一。

//编辑2:

使用BCMath编写了一个函数,我现在在 Windows 上,正在努力为 GMP 寻找正确的 dll。

function dechex32($i) {
    //Cast string
    $i = (string)$i;
    //Initialize result string
    $r = NULL;
    //Map hex values 0-9, a-f to array keys
    $hex = array_merge(range(0, 9), range('a', 'f'));
        //While input is lagrer than 0
        while(bccomp($i, '0') > 0) {
            //Modulo 16 and append hex char to result
            $r.= $hex[$mod = bcmod($i, '16')];
            //i = (i - mod) / 16
            $i = bcdiv(bcsub($i, $mod), '16');
        }
    //Reverse result and return
    return strrev($r);
}

var_dump(dechex32(12345678900));
/*string(9) "2dfdc1c34"*/

没有彻底测试,但似乎工作。作为最后的手段使用 - 100,000 次迭代的粗略基准测试确实表明,它比原生实现慢了约 40 倍。

于 2011-05-09T23:14:52.773 回答