如何获取结构数据的hexdump

....
 finalize(char *hdrs,sendip_data *headers[],int index,sendip_data *data,sendip_data *pack)
 {

 ........

出于调试目的,我想要数据和包结构的十六进制转储,其类型为sendip_data,这是一个非常复杂的结构.实际上它们包含一些二进制信息,所以我不确定我的项目的输出是否正确.因此,出于调试目的,我想将数据写入文件,以便我可以使用hexdump,如下所示 –

$hexdump -C file.txt

另外因为这是一个n / w数据包的运行时生成所以我也不确定数据和包结构的长度,我认为fread / fwrite将需要..所以请建议我一些东西.

解决方法

以下代码将为您提供代码中任意内存的十六进制转储.

#include <stdio.h>

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

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

    if (len == 0) {
        printf("  ZERO LENGTH\n");
        return;
    }
    if (len < 0) {
        printf("  NEGATIVE LENGTH: %i\n",len);
        return;
    }

    // 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;
}

您将一个描述,内存地址和长度传递给hexDump,它将输出一个十六进制转储(包括字符数据)以供检查.使用包含的main运行它时,输出为:

my_str:
  0000  61 20 63 68 61 72 20 73 74 72 69 6e 67 20 67 72  a char string gr
  0010  65 61 74 65 72 20 74 68 61 6e 20 31 36 20 63 68  eater than 16 ch
  0020  61 72 73 00                                      ars.

相关文章

一.C语言中的static关键字 在C语言中,static可以用来修饰局...
浅谈C/C++中的指针和数组(二) 前面已经讨论了指针...
浅谈C/C++中的指针和数组(一)指针是C/C++...
从两个例子分析C语言的声明 在读《C专家编程》一书的第三章时...
C语言文件操作解析(一)在讨论C语言文件操作之前,先了解一下...
C语言文件操作解析(三) 在前面已经讨论了文件打开操作,下面...