Code snippets:hexdump

From C

Jump to: navigation, search
 #include <stddef.h>
 #include <stdio.h>
 #include <ctype.h>
 
 static void hexdump(const void * memory, size_t bytes);
 
 int main(void) {
     unsigned char ascii[256];
     int i;
 
     for (i = 0; i < sizeof ascii; ++i)
       ascii[i] = i;
     hexdump(ascii, sizeof ascii);
     return 0;
   }
 
 static void hexdump(const void * memory, size_t bytes) {
     const unsigned char * p, * q;
     int i;
 
     p = memory;
     while (bytes) {
         q = p;
         printf("%p: ", (void *) p);
         for (i = 0; i < 16 && bytes; ++i) {
             printf("%02X ", *p);
             ++p;
             --bytes;
           }
         bytes += i;
         while (i < 16) {
             printf("XX ");
             ++i;
           }
         printf("| ");
         p = q;
         for (i = 0; i < 16 && bytes; ++i) {
             printf("%c", isprint(*p) && !isspace(*p) ? *p : ' ');
             ++p;
             --bytes;
           }
         while (i < 16) {
             printf(" ");
             ++i;
           }
         printf(" |\n");
       }
     return;
   }
Personal tools