user3436467 - 2 years ago 209
PHP Question

# php convert decimal to hexidecimal

I am extracting a serial from a digital certificate using the built in openssl library, however i am having trouble converting this number to hex with precision.

The extracted number is originally in decimal but i need to have it in hex.

The number I am trying to convert is: 114483222461061018757513232564608398004

Here is what I've tried:

• `dechex()`
did not work, it returns:
`7fffffffffffffff`

The closest I could get was this function from the php.net page but it does not convert the whole number on part of it.

``````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
``````

Here is what I am expected:

• Decimal number: 114483222461061018757513232564608398004

• Expected hex: 5620AAA80D50FD70496983E2A39972B4

I can see the correction conversion here:
https://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html

I need a php solution.

Answer Source

The problem is that `The largest number that can be converted is ... 4294967295` - hence why it's not working for you.

This answer worked for me during a quick test, assuming you have bcmath installed on your server, and you can obtain the number as a string to start with. If you can't, i.e. it begins life as numeric variable, you'll immediately reach 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;
}
``````

Example:

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

Ensure you pass a string into that function, not a numeric variable. In the example you provided in the question, it looks like you can obtain the number as a string initially, so should work if you have bc installed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download