我正在使用内置的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
-因此为什么它不适合你。
// 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,应该可以工作。
这是一个大整数,所以您需要使用像GMP这样的大整数库:
echo gmp_strval('114483222461061018757513232564608398004', 16);
// output: 5620aaa80d50fd70496983e2a39972b4
回答。如何转换一个巨大的整数十六进制在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);
尝试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);
?>