// Dumps raw memory in hex byte and printable split format
void dump(const unsigned char *data_buffer, const unsigned int length) {
   unsigned char byte;
   unsigned int i, j;
   for(i=0; i < length; i++) {
      byte = data_buffer[i];
      printf("%02x ", data_buffer[i]);  // Display byte in hex.
      if(((i%16)==15) || (i==length-1)) {
         for(j=0; j < 15-(i%16); j++)
            printf("   ");
         printf("| ");
         for(j=(i-(i%16)); j <= i; j++) {  // Display printable bytes from line.
            byte = data_buffer[j];
            if((byte > 31) && (byte < 127)) // Outside printable char range
               printf("%c", byte);
            else
               printf(".");
         }
         printf("\n"); // End of the dump line (each line is 16 bytes)
      } // End if
   } // End for
}

Hey guys i Found this code on the Net somewhere.
What it does it is written on the top of it .

I am facing problems understanding this function...

if(((i%16)==15) || (i==length-1)) {
         for(j=0; j < 15-(i%16); j++)
            printf("   ");
         printf("| ");
         for(j=(i-(i%16)); j <= i; j++) {  // Display printable bytes from line.
            byte = data_buffer[j];
            if((byte > 31) && (byte < 127)) // Outside printable char range
               printf("%c", byte);
            else
               printf(".");

I am not getting what is exactly happening in this loop!!!

Need you help guys please explain me this..

The % operator is modulo: Remainder after dividing the first operand by the second. The comments are actually helpful.

Yeah i know that but can you explain me the loop what happens exactly..

Line one explains what the program does. The loop in question is the 'printable' part of the split format. It is made a little more complex than it would otherwise need to be because it has to deal with a final output line that might be shorter than 16 bytes of data.

PS: In case it isn't obvious, I'm deliberately not explaining this: You need to understand it for yourself. Try walking through the code while it handles, say this string as bytes: "data". If you are still confused, handle "is eighteen bytes" so you can see it handle the first sixteen bytes, then the next two (or three if you count the trailing 0)

The first IF if(((i%16)==15) || (i==length-1)) basically tests if 16 bytes have been output -- the number of bytes needed for one line.
Within the IF, reoutput the same bytes as ASCII characters after a '|'.

The best way to understand this stuff is write down all the variables you see in the code in one column. Next to each variable write down the current values (if known). Then follow the code line by line writing down the changes in each variable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.