我正在使用内置的OpenSSL库从数字证书中提取序列号,但是,我无法将此数字精确地转换为十六进制。
提取的数字最初为十进制,但我需要为十六进制。
我要转换的数字是:11448322246106101871871321325645646083004
这是我尝试过的:
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
这是我所期望的:
我可以在这里看到更正转换:https : //www.mathsisfun.com/binary-decimal-hexadecimal-converter.html
我需要一个PHP解决方案。
问题是在于The largest number that can be converted is ... 4294967295
-因此,为什么它不为你工作。
假设您已经在服务器上安装了bcmath,那么在快速测试期间,此答案对我有用,并且您可以将数字作为字符串来获取。如果不能,即它作为数字变量开始使用,那么您将立即达到PHP的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,它应该可以工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句