본문 바로가기

Programming/C/C++

HEX dump

[출처] : http://stackoverflow.com/questions/7775991/how-to-get-hexdump-of-a-structure-data



#include <stdio.h>

void hexDump (char *desc, void *addr, int len) {
    int i;
    unsigned char buff[17];
    unsigned char *pc = (unsigned char*)addr;

    // Output description if given.
    if (desc != NULL)
        printf ("%s:\n", desc);

    // Process every byte in the data.
    for (i = 0; i < len; i++) {
        // Multiple of 16 means new line (with line offset).

        if ((i % 16) == 0) {
            // Just don't print ASCII for the zeroth line.
            if (i != 0)
                printf ("  %s\n", buff);

            // Output the offset.
            printf ("  %04x ", i);
        }

        // Now the hex code for the specific character.
        printf (" %02x", pc[i]);

        // And store a printable ASCII character for later.
        if ((pc[i] < 0x20) || (pc[i] > 0x7e))
            buff[i % 16] = '.';
        else
            buff[i % 16] = pc[i];
        buff[(i % 16) + 1] = '\0';
    }

    // Pad out last line if not exactly 16 characters.
    while ((i % 16) != 0) {
        printf ("   ");
        i++;
    }

    // And print the final ASCII bit.
    printf ("  %s\n", buff);
}

int main (int argc, char *argv[]) {
    char my_str[] = "a char string greater than 16 chars";
    hexDump ("my_str", &my_str, sizeof (my_str));
    return 0;
}



void HexDump(char* desc, unsigned char* data, int len)

{

int i = 0;

unsigned char buff[17];

unsigned char *pc = data;


// Output description if given.

if ( desc ) {

printf("%s:\n", desc);

}


// Process every byte in the data.

for (i = 0; i < len; i++)

{

// Multiple of 16 means new line (with line offset).

if ((i % 16) == 0)

{

// Just don't print ASCII for the zeroth line.

if (i != 0) {

printf("  %s\n", buff);

}


// Output the offset.

printf("  %04x ", i);

}


// Now the hex code for the specific character.

printf(" %02x", pc[i]);


// And store a printable ASCII character for later.

if ((pc[i] < 0x20) || (pc[i] > 0x7e)) {

buff[i % 16] = '.';

}

else {

buff[i % 16] = pc[i];

}


buff[(i % 16) + 1] = '\0';

}


// Pad out last line if not exactly 16 characters.

while ((i % 16) != 0) {

printf("   ");

i++;

}


// And print the final ASCII bit.

printf("  %s\n", buff);

}


'Programming > C/C++' 카테고리의 다른 글

std::find 클래스 멤버로 찾기  (0) 2014.12.11
c언어 매크로 사용법 - 1. #, ## 연산자  (0) 2014.12.05
C Timer 만들어 사용하기.  (0) 2014.11.08
C++ 마스터로 가는길..  (0) 2014.10.07
printf format  (0) 2014.09.04