PHP convert string to hex and hex to string

JoeNguyen picture JoeNguyen · Feb 3, 2013 · Viewed 211k times · Source

I got the problem when convert between this 2 type in PHP. This is the code I searched in google

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


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

I check it and found out this when I use XOR to encrypt.

I have the string "this is the test", after XOR with a key, I have the result in string ↕↑↔§P↔§P ♫§T↕§↕. After that, I tried to convert it to hex by function strToHex() and I got these 12181d15501d15500e15541215712. Then, I tested with the function hexToStr() and I have ↕↑↔§P↔§P♫§T↕§q. So, what should I do to solve this problem? Why does it wrong when I convert this 2 style value?

Answer

Philippe Gerber picture Philippe Gerber · Apr 27, 2018

For people that end up here and are just looking for the hex representation of a (binary) string.

bin2hex("that's all you need");
# 74686174277320616c6c20796f75206e656564

hex2bin('74686174277320616c6c20796f75206e656564');
# that's all you need

Doc: bin2hex, hex2bin.