2008/11/23 Rob Malpass <lug@???>:
> Hi all
>
> I need to find a litttle utility to display the contents of a binary file in
> some meaningful manner. I've tried od and hexdump and (it maybe me and
> syntax) but I can't get it quite right. I realise I could just do cat fred
> where fred is the file but that will throw out lots of non-printable stuff
> that'll just crash the terminal or send garbage to my printer (well perhaps
> not nowadays but older users will know what I mean here!).
>
> Say if I have a file which says "foo bar" then what I want is
>
> 0000 b1 b2 b3 b4 b5 b6 b7 foo bar.
>
> i.e. displaying a . for every non-printable character. I can make hexdump
> and od do the byte listings but I can't see how to get them to output the
> ASCII itself - they'll output the hex or octal no problem. Can someone
> either correct my syntax or show me a decent little utility to do the same
> job?
>
od -t x1a
Will give you single byte hex, plus ascii. You will get the names of
non-printable characters instead of '.'s and the ascii will be spaced
out.
Alternatively, it should be easy to do in perl.
Here is a C version I knocked up:
#include <stdio.h>
#include <ctype.h>
#define COLUMNS 8
int main(int argc, char** argv) {
int c, col, offset, i;
char buffer[COLUMNS];
if (argc != 1) {
fputs("usage: hexascii < filename", stderr);
return 1;
}
col = 0; offset = 0;
while ((c=getchar()) != EOF) {
if (col == 0) {
printf("%04x\t%02x", offset, c);
} else {
printf(" %02x", c);
}
buffer[col++] = isprint(c) ? c : '.';
offset++;
if (col >= COLUMNS) {
col = 0;
putchar('\t');
for (i = 0; i < COLUMNS; i++) {
putchar(buffer[i]);
}
putchar('\n');
}
}
if (col > 0) {
putchar('\t');
for (i = 0; i < col; i++) {
putchar(buffer[i]);
}
putchar('\n');
}
return 0;
}
save it as hexascii.c
compile it with gcc -o hexascii hexascii.c
run it as ./hexascii < somefile
Jim