Skip to content

Instantly share code, notes, and snippets.

@ktomk
Created June 13, 2011 18:02
Show Gist options
  • Save ktomk/1023318 to your computer and use it in GitHub Desktop.
Save ktomk/1023318 to your computer and use it in GitHub Desktop.
Dump a string in a hexidecimal representation similar to terminal based hex-editors.
<?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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment