Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex to ascii characters

Is it possible to represent a sequence of hex characters (0-9A-F) with a sequence of 0-9a-zA-Z characters, so the the result sequence is smaller and can be decoded?

For example:

$hex = '5d41402abc4b2a76b9719d911017c592';
echo $string = encode($hex); // someASCIIletters123
echo decode(string) == $hex; //true
like image 705
Dziamid Avatar asked Sep 20 '11 16:09

Dziamid


4 Answers

The built-in php functions may help some landing here on a search:

// https://www.php.net/manual/en/function.hex2bin
$hex = '6578616d706c65206865782064617461';
echo hex2bin($hex); // example hex data
like image 168
Alex Taylor Avatar answered Sep 19 '22 18:09

Alex Taylor


I think you're looking for this:

function hex2str($hex) {
    $str = '';
    for($i=0;$i<strlen($hex);$i+=2) $str .= chr(hexdec(substr($hex,$i,2)));
    return $str;
}

(From http://www.linux-support.com/cms/php-convert-hex-strings-to-ascii-strings/) (Works like this javascript tool: http://www.dolcevie.com/js/converter.html)

like image 29
Andrew Avatar answered Nov 18 '22 18:11

Andrew


You mean want to convert a string of hex digits into actual hex values?

$hex_string = "A1B2C3D4F5"; // 10 chars/bytes
$packed_string = pack('H*', $hex_string); // 0xA1B2C3D4F5 // 5 chars/bytes.
like image 18
Marc B Avatar answered Nov 18 '22 16:11

Marc B


You can trivially adapt the solution I presented here using the function base_convert_arbitrary.

Edit: I had not read carefully enough :) Base 16 to base 62 is still very doable, as above.

See it in action.

like image 5
Jon Avatar answered Nov 18 '22 18:11

Jon