刚刚查找了处理此问题的Zend_Crypt_Math_BigInteger_Bcmath
代码Zend_Crypt_Math_BigInteger_Gmp
:
使用 BCmath (Big-Endian)
这基本上是Chad Birch发布的解决方案。
public static function bc_binaryToInteger($operand)
{
$result = '0';
while (strlen($operand)) {
$ord = ord(substr($operand, 0, 1));
$result = bcadd(bcmul($result, 256), $ord);
$operand = substr($operand, 1);
}
return $result;
}
使用 GMP(大端)
相同的算法 - 只是不同的函数名称。
public static function gmp_binaryToInteger($operand)
{
$result = '0';
while (strlen($operand)) {
$ord = ord(substr($operand, 0, 1));
$result = gmp_add(gmp_mul($result, 256), $ord);
$operand = substr($operand, 1);
}
return gmp_strval($result);
}
将算法更改为使用 Litte-Endian 字节顺序非常简单:只需从头到尾读取二进制数据:
使用 BCmath (Litte-Endian)
public static function bc_binaryToInteger($operand)
{
// Just reverse the binray data
$operand = strrev($operand);
$result = '0';
while (strlen($operand)) {
$ord = ord(substr($operand, 0, 1));
$result = bcadd(bcmul($result, 256), $ord);
$operand = substr($operand, 1);
}
return $result;
}
使用 GMP (Litte-Endian)
public static function gmp_binaryToInteger($operand)
{
// Just reverse the binray data
$operand = strrev($operand);
$result = '0';
while (strlen($operand)) {
$ord = ord(substr($operand, 0, 1));
$result = gmp_add(gmp_mul($result, 256), $ord);
$operand = substr($operand, 1);
}
return gmp_strval($result);
}