hexoutput() in PHP and C Posted: (2005-02-28) Viewed: (2414 times)
hexoutput (PHP)
hexoutput (C)
Code (PHP):
// Function found at: http://www.theserverpages.com/scripts/
// Please leave this comment intact when using this code!
function hexoutput($data, $width=16) {
$st=0;
$txt="";
$out="";
for ($i=0; $i<strlen($data); $i++) {
$n=ord(substr($data,$i,1));
$c=str_pad(dechex($n),2,"0",STR_PAD_LEFT);
$out.=$c." ";
if ($n==32 || $n>32 && $n<127 || $n>160) {
$txt.=substr($data,$i,1);
} else {
$txt.=".";
}
if ($i % $width == $width-1) {
$out.="| ".$txt."\n";
$txt="";
}
}
$out.=str_repeat(" ",$width-($i % $width));
$out.="| ".$txt;
$out.="\n";
return $out;
}
Example Usage (PHP):
$data=fgets($fp,40960);
echo hexoutput($data);
Example Output (PHP):
00 6d 70 5f 68 6f 73 74 61 67 65 70 65 6e 61 6c | .mp_hostagepenal
74 79 00 31 33 00 6d 70 5f 61 75 74 6f 74 65 61 | ty.13.mp_autotea
6d 62 61 6c 61 6e 63 65 00 31 00 6d 70 5f 6d 61 | mbalance.1.mp_ma
78 72 6f 75 6e 64 73 00 30 00 6d 70 5f 72 6f 75 | xrounds.0.mp_rou
6e 64 74 69 6d 65 00 35 00 6d 70 5f 66 72 65 65 | ndtime.5.mp_free
7a 65 74 69 6d 65 00 32 00 6d 70 5f 63 34 74 69 | zetime.2.mp_c4ti
6d 65 72 00 34 35 00 6d 70 5f 6c 69 6d 69 74 74 | mer.45.mp_limitt
65 61 6d 73 00 32 00 6d 70 5f 74 65 61 6d 70 6c | eams.2.mp_teampl
61 79 00 30 00 6d 70 5f 66 72 61 67 6c 69 6d 69 | ay.0.mp_fraglimi
74 00 30 00 6d 70 5f 66 61 6c 6c 64 61 6d 61 67 | t.0.mp_falldamag
65 00 30 00 6d 70 5f 77 65 61 70 6f 6e 73 74 61 | e.0.mp_weaponsta
79 00 30 00 6d 70 5f 66 6f 72 63 65 72 65 73 70 | y.0.mp_forceresp
Code (C):
#include <stdio.h>
#include <string.h>
// Function found at: http://www.theserverpages.com/scripts/
// Please leave this comment intact when using this code!
void hexoutput(char *src, int len, int width) {
if (len<0) return;
if (width>32) width=32;
unsigned char c;
char buffer[33];
int rem=0;
int jb=0;
int bwidth=width-1;
buffer[width]=0x00;
for (int i=0; i<len; i++) {
c=src[i];
if (c>=32 && c<127 || c>160) {
buffer[jb++]=(char)c;
} else {
buffer[jb++]='.';
}
printf("%02X ",c);
if ( i%width==bwidth ) {
jb=0;
printf("| %s\n",buffer);
}
}
for (int i=(len % width); i<width; i++) {
buffer[jb++]=' ';
printf(" ",i);
}
printf("| %s\n",buffer);
}
Example Usage (C):
int main() {
char txt[]="Hi, how are you today?";
hexoutput(txt, strlen(txt), 16);
return 1;
}
Example Output (C):
48 69 2C 20 68 6F 77 20 61 72 65 20 79 6F 75 20 | Hi, how are you
74 6F 64 61 79 3F | today?
|