繁体   English   中英

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

[英]php convert decimal to hexadecimal

我正在使用内置的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解决方案。

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

这个答案在快速测试期间适用于我,假设您已在服务器上安装了bcmath, 并且您可以将该数字作为字符串开头 如果你不能,即它开始作为数字变量生活,你将立即达到PHP的浮动限制

// 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,则应该可以使用。

由lafor回答。 如何在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);

这是一个大整数,因此您需要使用像GMP这样的大整数库:

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

试试这个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);

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM