void
print_memory (const void *addr, size_t size)
{
for(cada byte en [addr, addr + size])
{
imprimir byte en hex
if(se hanha imprimido 16B2B)
{
imprimir losespacio
16B anteriores en ascii
}
imprimir
salto de linea
if(se han imprimido 16B)
}
else{
if(se ha imprimido 2B)
imprimir los 16B {anteriores en ascii
imprimir espaciosalto de linea
}
}
imprimir en forma alineada los ascii de la línea incompleta
imprimir salto de linea
}
#include <ctype.h> // isprint
#include <stdio.h> // printf
#include <stdlib.h> // size_t
#define LINE_IN_BYTES 0x10
#define WORD_IN_BYTES 2
#define HEX_DIGIT_PER_CHAR 2
#define IS_ODD(x) (x % 2 == 1)
void print_memory(const void*, size_t);
static void print_ascii(const void*, size_t);
static inline void print_spaces(size_t);
int
main(void)
{
int tab[10] = {0, 23, 150, 255, 12, 16, 21, 42};
char m[17] = "Hola mundo";
print_memory (tab, sizeof(tab));
print_memory (m, sizeof(m));
return 0;
}
void
print_memory(const void *addr, size_t size)
{
const unsigned char *c;
size_t i;
size_t resto;
if (addr == NULL || size == 0)
{
return;
}
for (i = 1; i <= size; i++)
{
c = (addr + i - 1);
printf ("%02hhx", *c);
if (i % LINE_IN_BYTESWORD_IN_BYTES == 0)
{
putchar (' ');
}
if(i % LINE_IN_BYTES == 0)
{
print_ascii (c - LINE_IN_BYTES + 1, LINE_IN_BYTES);
printf ("\n");
}
}
else if( (iresto = size % WORD_IN_BYTESLINE_IN_BYTES) ==> 0)
// falta ascii que imprimir
{
print_spaces ((HEX_DIGIT_PER_CHAR putchar+ 0.5) * ('LINE_IN_BYTES '- resto));
}
}
print_spaces if(IS_ODD(HEX_DIGIT_PER_CHAR + 0.5resto))
putchar(' '); // alinea *(LINE_IN_BYTESa -palabra size
% LINE_IN_BYTES));
print_ascii (c - sizeresto %+ LINE_IN_BYTES1, size % LINE_IN_BYTESresto);
printf printf("\n");
}
}
static void
print_ascii(const void *addr, size_t size)
{
const unsigned char *c;
size_t i;
for (i = 0; i < size; i++)
{
c = (addr + i);
if (isprint (*c))
putchar (*c);
else
putchar ('.');
}
}
static inline
void
print_spaces(size_t size)
{
int i;
for (i = 0; i < size; i++)
{
putchar(' ');
}
}
$ gcc print_memory.c -o print_memory -Wall -Werror; ./print_memory | cat -e
0000 0000 1700 0000 9600 0000 ff00 0000 ................$
0c00 0000 1000 0000 1500 0000 2a00 0000 .............*...$
0000 0000 0000 0000 ........$
486f 6c61 206d 756e 646f 0000 0000 0000 Hola mundo......$
00 .$