4

在 32 位系统上将编码为十六进制字符串的 64 位整数转换为十进制字符串的简单方法是什么。它必须是完整值,不能是科学计数法或截断:/

“0c80000000000063”==“900719925474099299”

“0c80000000000063”!= 9.007199254741E+17

PHP 的 base_convert() 和 hexdec() 不能正确完成这项工作。

4

2 回答 2

2

您需要使用BC Math PHP 扩展(捆绑)。

首先拆分您的输入字符串以获得高字节和低字节,然后将其转换为十进制,然后通过 BC 函数进行计算,如下所示:

$input = "0C80000000000063";

$str_high = substr($input, 0, 8);
$str_low = substr($input, 8, 8);

$dec_high = hexdec($str_high);
$dec_low  = hexdec($str_low);

//workaround for argument 0x100000000
$temp = bcmul ($dec_high, 0xffffffff);
$temp2 = bcadd ($temp, $dec_high);

$result = bcadd ($temp2, $dec_low);

echo $result;

/*
900719925474099299
*/
于 2012-08-12T02:22:25.670 回答
1

您是否在 php.net 上看到了 hexdec 帮助页面的第一条评论?

当给定大数时,hexdec 函数会自动将值转换为科学计数法。因此,“aa1233123124121241”作为十六进制值将转换为“3.13725790445E+21”。如果要转换表示哈希值(md5 或 sha)的十六进制值,则需要该表示的每一位以使其有用。通过使用 number_format 函数,您可以完美地做到这一点。例如 :

<?php

            // Author: holdoffhunger@gmail.com

        // Example Hexadecimal
        // ---------------------------------------------

    $hexadecimal_string = "1234567890abcdef1234567890abcdef";

        // Converted to Decimal
        // ---------------------------------------------

    $decimal_result = hexdec($hexadecimal_string);

        // Print Pre-Formatted Results
        // ---------------------------------------------

    print($decimal_result);

            // Output Here: "2.41978572002E+37"
            // .....................................

        // Format Results to View Whole All Digits in Integer
        // ---------------------------------------------

            // ( Note: All fractional value of the
            //         Hexadecimal variable are ignored
            //         in the conversion. )

    $current_hashing_algorithm_decimal_result = number_format($decimal_result, 0, '', '');

        // Print Formatted Results
        // ---------------------------------------------

    print($current_hashing_algorithm_decimal_result);

            // Output Here: "24197857200151253041252346215207534592"
            // .....................................

?>
于 2012-08-08T15:38:59.823 回答