#include <stdio.h>
#include <string.h>
static void hexdump_small_dump(FILE *, void *, unsigned, unsigned);
void hex_dump (FILE * stream, void * data, unsigned length, unsigned initial_offset, int show_header) {
if (!(stream && data && length)) return;
if (show_header) fprintf(stream,
" 00 01 02 03 04 05 06 07 - 08 09 0A 0B 0C 0D 0E 0F 0123456789ABCDEF\n"
"--------- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ----------------\n");
if ((length + (initial_offset % 16)) <= 16) {
hexdump_small_dump(stream, data, length, initial_offset);
return;
}
unsigned char * dp = data;
if (initial_offset % 16) {
unsigned char initseg = 16 - (initial_offset % 16);
hexdump_small_dump(stream, data, initseg, initial_offset);
dp += initseg;
initial_offset += initseg;
length -= initseg;
}
char line[82];
char buf[10];
unsigned char pos;
while (length >= 16) {
strcpy(line,
/* 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 */
"********: ?? ?? ?? ?? ?? ?? ?? ?? - ?? ?? ?? ?? ?? ?? ?? ?? ................\n");
sprintf(buf, "%08X", initial_offset);
memcpy(line, buf, 8);
for (pos = 0; pos < 16; pos ++) {
sprintf(buf, "%02hhX", dp[pos]);
memcpy(line + 10 + 3 * pos + (pos / 4) + (pos / 8), buf, 2);
if ((dp[pos] >= 32) && (dp[pos] <= 126)) line[63 + pos] = dp[pos];
}
fprintf(stream, "%s", line);
dp += 16;
initial_offset += 16;
length -= 16;
}
if (length) hexdump_small_dump(stream, dp, length, initial_offset);
}
static void hexdump_small_dump (FILE * stream, void * data, unsigned length, unsigned initial_offset) {
char line[81];
char buf[10];
unsigned char start, pos, end;
memset(line, ' ', 79);
line[79] = '\n';
line[80] = 0;
line[8] = ':';
start = initial_offset % 16;
initial_offset &= ~15;
end = start + length;
sprintf(buf, "%08X", initial_offset);
memcpy(line, buf, 8);
if ((start < 8) && (end > 8)) line[35] = '-';
for (pos = start; pos < end; pos ++) {
sprintf(buf, "%02hhX", (pos - start)[(unsigned char *) data]);
memcpy(line + 10 + 3 * pos + (pos / 4) + (pos / 8), buf, 2);
line[63 + pos] = (((pos - start)[(unsigned char *) data] >= 32) && ((pos - start)[(unsigned char *) data] <= 126)) ?
(pos - start)[(unsigned char *) data] : '.';
}
fprintf(stream, "%s", line);
}
Comments