cskwrd
cskwrd

Reputation: 2885

How do I convert a string that looks like a hex number to an actual hex number in php?

I have a string that looks like this "7a" and I want to convert it to the hex number 7A. I have tried using pack and unpack but that is giving me the hex representation for each individual character.

Upvotes: 13

Views: 10700

Answers (3)

aforankur
aforankur

Reputation: 1293

This can by try -

function strToHex($string)
{
$hex='';
for ($i=0; $i < strlen($string); $i++)
{
    $hex .= dechex(ord($string[$i]));
}
return $hex;
}

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 817198

Well a number is a number, it does not depend on the representation. You can get the actual value using intval():

$number = intval('7a', 16); 

To convert the number back to a hexadecimal string you can use dechex().

Upvotes: 9

Peter Bailey
Peter Bailey

Reputation: 105914

Probably the simplest way to store that as an integer is hexdec()

$num = hexdec( '7A' );

Upvotes: 25

Related Questions