String2Hex and Hex2String

Convert hex to string and vice versa.

function String2Hex($string){
    $hex='';
    for ($i=0; $i < strlen($string); $i++){
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}
 
 
function Hex2String($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}
 
// example:
 
$hex = String2Hex("test sentence...");
// $hex contains 746573742073656e74656e63652e2e2e
 
print Hex2String($hex);
// outputs: test sentence...
Snippet Details




Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

Alex Rath April 17, 2010 at 19:31
<?php

//By Alexander Rath
// Improvements:
// - Chars under 0x10 now work
// - Cleaner Code
// - Speed Improvements

//Notice that this does not REALLY return a Hex,
//it returns a String containing the Hex...
//(otherwise Strings would have to be pretty short on a 64bit Enviroment :P)

function str2hex($func_string) {
$func_retVal = '';
$func_length = strlen($func_string);
for($func_index = 0; $func_index < $func_length; ++$func_index) $func_retVal .= ((($c = dechex(ord($func_string{$func_index}))) && strlen($c) & 2) ? $c : "0{$c}");

return strtoupper($func_retVal);
}

function hex2str($func_string) {
$func_retVal = '';
$func_length = strlen($func_string);
for($func_index = 0; $func_index < $func_length; ++$func_index) $func_retVal .= chr(hexdec($func_string{$func_index} . $func_string{++$func_index}));

return $func_retVal;
}

//Example:
$hex = str2hex("This is my Test StringnEven Multiline works now!");
echo "{$hex}n"; //Outputs "54686973206973206D79205465737420537472696E670A4576656E204D756C74696C696E6520776F726B73206E6F7721"
echo hex2str($hex) . "n"; //Outputs "This is my Test String
// Even Multiline works now!"

?>
Alex Rath April 17, 2010 at 19:12
There is a bug:
<?php

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


function Hex2String($hex){
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2){
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}

// example:

$hex = String2Hex("This isnmultiline :)");
// $hex contains 54686973206973a6d756c74696c696e65203a29
// Notice the a between 54686973206973 and 6d756c74696c696e65203a29
// Hex2String expects that every char was converted to 2 chars, but
// since n equals to dec 10 which is hex a (and not 0a), it returns
// some weird mess

print Hex2String($hex);
// outputs: This is??V?F?Ɩ?R?

?>