Monday, September 19, 2011

Convert String to Hexadecimal in PHP

bin2hex($string) will solve this problem. Don't get confused by the word bin in the function.

When I searched for converting a string to hexadecimal, in most of the blogs/Forums i got the following function.

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

But when i tried to compare the output of above function with bin2hex (inbuilt PHP function), both got the same result.

Conclusion is if you want to convert a string into an hexadecimal string, then it's better to use bin2hex insted of the above function.

I tested it with the following example
"sfkjsd38jsdkjfD83kkksJADHAJ#$#JDKEHdjh843j4hjkDS&@)HDHSJKDHADASDSWE(Y#JDHSA*&#JKD3423523Sd"

No comments: