Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

logging - Off-the-Shelf C++ Hex Dump Code

I work a lot with network and serial communications software, so it is often necessary for me to have code to display or log hex dumps of data packets.

Every time I do this, I write yet another hex-dump routine from scratch. I'm about to do so again, but figured I'd ask here: Is there any good free hex dump code for C++ out there somewhere?

Features I'd like:

  • N bytes per line (where N is somehow configurable)
  • optional ASCII/UTF8 dump alongside the hex
  • configurable indentation, per-line prefixes, per-line suffixes, etc.
  • minimal dependencies (ideally, I'd like the code to all be in a header file, or be a snippet I can just paste in)

Edit: Clarification: I am looking for code that I can easily drop in to my own programs to write to stderr, stdout, log files, or other such output streams. I'm not looking for a command-line hex dump utility.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I often use this little snippet I've written long time ago. It's short and easy to add anywhere when debugging etc...

#include <ctype.h>
#include <stdio.h>

void hexdump(void *ptr, int buflen) {
  unsigned char *buf = (unsigned char*)ptr;
  int i, j;
  for (i=0; i<buflen; i+=16) {
    printf("%06x: ", i);
    for (j=0; j<16; j++) 
      if (i+j < buflen)
        printf("%02x ", buf[i+j]);
      else
        printf("   ");
    printf(" ");
    for (j=0; j<16; j++) 
      if (i+j < buflen)
        printf("%c", isprint(buf[i+j]) ? buf[i+j] : '.');
    printf("
");
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...