How to covnert Hex to Dec int32 and vice versa in PHP?

0

Can someone suggest a best way to convert hex to dec and vice versa in PHP (equivalent to the PowerShell commands below)?

$hex = "0x80070020"
$hex2dec = [Convert]::ToInt32($hex,16) 
write-host $hex2dec #output: -2147024864

$dec = "-2147024864"
$dec2hex = "0x{0:X}" -f [Int]$hex 
write-host $dec2hex #output: 0x80070020

I tried following approach in PHP.

echo $val = hexdec(80070020) //returns Int64, need Int32.
echo $val = dechex(-2147024864) //returns ffffffff80070020, can use string replacement but wondering if there is any other best way.

Any suggestions appreciated.

php
asked on Stack Overflow Mar 9, 2019 by user11177254

2 Answers

0

You can simply truncate it to 32-bits:

$x = hexdec(1234) & 0xFFFFFFFF

If you need it to be signed you can simply subtract pow(2, 31) from it:

$x -= 0x80000000
answered on Stack Overflow Mar 9, 2019 by Kristopher Ives
0

For the hex > dec you could use:

$hex = '80070020';
$dec = unpack('l', pack('l', hexdec($hex)))[1];

This will put it into the 32bit binary representation and read it as signed 32bit int.

answered on Stack Overflow Mar 9, 2019 by kuh-chan

User contributions licensed under CC BY-SA 3.0