Dereleased

PHP HexDump Function

Jun 21st, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.89 KB | None | 0 0
  1. function hexdump($string) {
  2.     $data = array();
  3.     foreach (str_split($string, 16) as $line) {
  4.         $data[] = str_split($line);
  5.     }
  6.  
  7.     $output = "00 01 02 03 04 05 06 07   08 09 0A 0B 0C 0D 0E 0F   0123456789ABCDEF";
  8.     $linecount = 0;
  9.     foreach ($data as $datum) {
  10.         ++$linecount;
  11.         $line = str_repeat(" ", 68);
  12.         for ($i = 0; $i < count($datum); ++$i) {
  13.             if (empty($datum[$i])) {
  14.                 break 2;
  15.             }
  16.  
  17.             $chr = $datum[$i];
  18.             $pos = $i * 3 + ( $i > 7 ? 2 : 0 );
  19.             $hex = sprintf('%02X', ord($chr));
  20.  
  21.             $line[$pos] = $hex[0];
  22.             $line[$pos + 1] = $hex[1];
  23.  
  24.             $line[68 - 16 + $i] = ($chr >= ' ' && $chr <= 'z' ? $chr : '.');
  25.         }
  26.         $output .= "\n$line";
  27.     }
  28.  
  29.     $maxlen = max(2, strlen($linecount - 1));
  30.  
  31.     $output = explode("\n", $output);
  32.     for ($i = 1; $i < count($output); ++$i) {
  33.         $output[$i] = sprintf("%0{$maxlen}X %s", $i - 1, $output[$i]);
  34.     }
  35.  
  36.     return "-- " . implode("\n", $output);
  37. }
Add Comment
Please, Sign In to add comment