public
Created

Dump a string in a hexidecimal representation similar to terminal based hex-editors.

  • Download Gist
hex_dump.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
<?php
/*
* hex_dump.php
*
* Copyright 2011 mot <@fsfe.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
 
/**
* dump a string in hex notation
* next to the string data.
*
* nonprintable characters are displayed
* as .
*
* 16 characters per line, as an 8-char
* pair. Hexadecimal and decimal off-
* set values on each line.
*/
function hex_dump($string)
{
$len=strlen($string);
$rows=$len/16;
for($r=0; $r<$rows; $r++)
{
$offset=$r*16;
$hex = '';
$text = '';
for($i=0;$i<16&&$offset+$i<$len;$i++)
{
$pos = $offset+$i;
$char = $string[$pos];
$text .= ctype_print($char) ? $char : '.';
$hex .= sprintf('%02X ', ord($char));
if ($i==7)
{
$text.=' '; $hex.=' ';
}
}
printf("%02X %03d %-50s %s\n", $offset, $offset, rtrim($hex), $text);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.