php将十进制转换为十六进制

时间:2016-08-29 04:14:05

标签: php

我使用内置的OpenSSL库从数字证书中提取序列,但是,我无法精确地将此数字转换为十六进制。

提取的数字最初是十进制的,但我需要以十六进制表示。

我想转换的号码是:114483222461061018757513232564608398004

这是我尝试过的:

  • dechex()无效,它返回:7fffffffffffffff

我能得到的最接近的是来自php.net页面的这个函数,但是它并没有转换整个数字。

function dec2hex($dec) {
  $hex = ($dec == 0 ? '0' : '');

  while ($dec > 0) {
    $hex = dechex($dec - floor($dec / 16) * 16) . $hex;
    $dec = floor($dec / 16);
  }

  return $hex;
}
echo dec2hex('114483222461061018757513232564608398004');
//Result: 5620aaa80d50fc000000000000000000

这是我所期待的:

  • 十进制数:114483222461061018757513232564608398004
  • 预期十六进制:5620AAA80D50FD70496983E2A39972B4

我可以在这里看到更正转换: https://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html

我需要一个PHP解决方案。

4 个答案:

答案 0 :(得分:6)

问题是that The largest number that can be converted is ... 4294967295 - 因此它不适合你。

This answer在快速测试期间为我工作,假设您已在服务器上安装了bcmath,并且您可以将该数字作为字符串以开头。如果你不能,即它以数字变量开始,你就会立即到达PHP's float limit

// Credit: joost at bingopaleis dot com
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number)
{
    $hexvalues = array('0','1','2','3','4','5','6','7',
               '8','9','A','B','C','D','E','F');
    $hexval = '';
     while($number != '0')
     {
        $hexval = $hexvalues[bcmod($number,'16')].$hexval;
        $number = bcdiv($number,'16',0);
    }
    return $hexval;
}

示例:

$number = '114483222461061018757513232564608398004'; // Important: already a string!
var_dump(dec2hex($number)); // string(32) "5620AAA80D50FD70496983E2A39972B4"

确保将字符串传递给该函数,而不是数字变量。在您在问题中提供的示例中,看起来您最初可以将数字作为字符串获取,因此如果您安装了bc,则应该可以使用。

答案 1 :(得分:5)

由lafor回答。 How to convert a huge integer to hex in php?

function bcdechex($dec) 
{
    $hex = '';
    do {    
        $last = bcmod($dec, 16);
        $hex = dechex($last).$hex;
        $dec = bcdiv(bcsub($dec, $last), 16);
    } while($dec>0);
    return $hex;
}

Example:
$decimal = '114483222461061018757513232564608398004';
echo "Hex decimal : ".bcdechex($decimal);

答案 2 :(得分:4)

这是一个大整数,所以你需要使用像GMP这样的大整数库:

echo gmp_strval('114483222461061018757513232564608398004', 16);
// output: 5620aaa80d50fd70496983e2a39972b4

答案 3 :(得分:0)

尝试使用100%适用于任何数字

 <?php 
        $dec = '114483222461061018757513232564608398004';
     // init hex array
       $hex = array();
       while ($dec)
       {
         // get modulus // based on docs both params are string
          $modulus = bcmod($dec, '16');
          // convert to hex and prepend to array
          array_unshift($hex, dechex($modulus));
         // update decimal number
         $dec = bcdiv(bcsub($dec, $modulus), 16);
        }
       // array elements to string
       echo implode('', $hex);

?>
相关问题