PHP: Convert Ascii To Hex

PHP: Convert Ascii To HexWhen working in PHP there are times when I want to see what a string is in HEX – a lot of times there are invisible characters that or non-printing strings that can throw your program or script for a loop.

If you save the string to a text file, you can use a hex editor utility, like hexdump to take a look at the hex codes of the ASCII characters:

$ echo abcd > test.txt
$ hexdump test.txt
0000000 61 62 63 64 0a
0000005
$

Now for the PHP version:

header('Content-type: text/plain; charset=utf-8');
$ascii = 'abcd';
$hex = unpack('H*',$ascii);
// you can print out the hex result of the ascii conversion:
print_r($hex);
#   Array
#   (
#       [1] => 61626364
#   )
// or for a nicer display you can add spaces between every two characters
// and wrap the column every 6 characters (change to fit your needs)
echo wordwrap(implode(' ', str_split($hex[1], 2)), 6);
#   61 62
#   63 64

Related Posts:

This entry was posted in Tech Tips, Web Development and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>