Tuesday, July 13, 2004
hexview
Every programmer, regardless of the language in use, should write his/her own hex viewer, right? Well, this is mine. Years ago whenever I taught someone the C language, this was my damn favourite. And still, it's useful whenever I do some reverse engineering on Microsoft Excel file format.
It should compile in any platform. And just for the sake of completeness, building it using gcc 3.3 (Linux), plus additional compression with UPX, gives less than 7 KB executable file. Enjoy!
#include <stdio.h> int main( int argc, char** argv ) { FILE *f; unsigned char buf[16]; int i, j, k; if( argc < 2 ) return 0; f = fopen( argv[1], "rb" ); if( !f ) perror( "error" ); else { k = 0; while( !feof( f ) ) { j = fread( buf, 1, 16, f ); printf("%08x ", k ); k += j; for( i = 0; i < 16; i++ ) if( i < j ) printf("%02x ", buf[i] ); else printf(" "); printf(" "); for( i = 0; i < 16; i++ ) if( i < j ) printf("%c", (buf[i] > 31) ? buf[i] : '.'); else printf(" "); printf("\n"); } fclose( f ); } return 0; }
Comments:
<< Home
if( i < j ) printf("%c", (buf[i] > 31) ? buf[i] : '.');
bisa diimprove jadi (still ansi compliant)
#include < ctype.h >
if( i < j ) printf("%c", isprint(buf[i]) ? buf[i] : '.');
--
Joe
http://blog.compactbyte.com
bisa diimprove jadi (still ansi compliant)
#include < ctype.h >
if( i < j ) printf("%c", isprint(buf[i]) ? buf[i] : '.');
--
Joe
http://blog.compactbyte.com
Ack, I recall now why I hated isprint() once. This was because of the bug in old Borland C standard C library implementation, it was a macro: #define isprint(c) ((c) >= 0x20 && (c) <= 0x7e). You'll end up having fancy result when doing something like if( isprint(c++) ) do_something_with(c). Since then, avoiding isprint was my best practice (/me is paranoid).
But of course using other, non-buggy compiler, isprint() is definitely better.
Post a Comment
But of course using other, non-buggy compiler, isprint() is definitely better.
<< Home