Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a hex dump of a string in PHP?

I'm investigating encodings in PHP5. Is there some way to get a raw hex dump of a string? i.e. a hex representation of each of the bytes (not characters) in a string?

like image 417
Amandasaurus Avatar asked Jun 29 '09 10:06

Amandasaurus


People also ask

How does a hex dump work?

Hexdump is a utility that displays the contents of binary files in hexadecimal, decimal, octal, or ASCII. It's a utility for inspection and can be used for data recovery, reverse engineering, and programming.

What is PHP bin2hex?

The bin2hex() function converts a string of ASCII characters to hexadecimal values. The string can be converted back using the pack() function.


2 Answers

echo bin2hex($string); 

or:

for ($i = 0; $i < strlen($string); $i++) {     echo str_pad(dechex(ord($string[$i])), 2, '0', STR_PAD_LEFT); } 

$string is the variable which contains input.

like image 120
Stefan Gehrig Avatar answered Oct 17 '22 21:10

Stefan Gehrig


For debugging work with binary protocols, I needed a more traditional HEX dump, so I wrote this function:

function hex_dump($data, $newline="\n") {   static $from = '';   static $to = '';      static $width = 16; # number of bytes per line      static $pad = '.'; # padding for non-visible characters      if ($from==='')   {     for ($i=0; $i<=0xFF; $i++)     {       $from .= chr($i);       $to .= ($i >= 0x20 && $i <= 0x7E) ? chr($i) : $pad;     }   }      $hex = str_split(bin2hex($data), $width*2);   $chars = str_split(strtr($data, $from, $to), $width);      $offset = 0;   foreach ($hex as $i => $line)   {     echo sprintf('%6X',$offset).' : '.implode(' ', str_split($line,2)) . ' [' . $chars[$i] . ']' . $newline;     $offset += $width;   } } 

This produces a more traditional HEX dump, like this:

hex_dump($data);  =>   0 : 05 07 00 00 00 64 65 66 61 75 6c 74 40 00 00 00 [.....default@...] 10 : 31 42 38 43 39 44 30 34 46 34 33 36 31 33 38 33 [1B8C9D04F4361383] 20 : 46 34 36 32 32 46 33 39 32 46 44 38 43 33 42 30 [F4622F392FD8C3B0] 30 : 45 34 34 43 36 34 30 33 36 33 35 37 45 35 33 39 [E44C64036357E539] 40 : 43 43 38 44 35 31 34 42 44 36 39 39 46 30 31 34 [CC8D514BD699F014] 

Note that non-visible characters are replaced with a period - you can change the number of bytes per line ($width) and padding character ($pad) to suit your needs. I included a $newline argument, so you can pass "<br/>" if you need to display the output in a browser.

like image 38
mindplay.dk Avatar answered Oct 17 '22 21:10

mindplay.dk