Skip to content

Instantly share code, notes, and snippets.

@eduard93
Forked from ccbrown/DumpHex.c
Created January 17, 2019 17:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eduard93/3b299b4e344ab56ce05521acb96c1ba7 to your computer and use it in GitHub Desktop.
Save eduard93/3b299b4e344ab56ce05521acb96c1ba7 to your computer and use it in GitHub Desktop.
Compact C Hex Dump Function w/ASCII
#include <stdio.h>
char* DumpHex2(const void* data, size_t size) {
const int symbolSize = 100;
char* buffer = calloc(10*size, sizeof(char));
char* symbol = calloc(symbolSize, sizeof(char));
char ascii[17];
size_t i, j;
ascii[16] = '\0';
for (i = 0; i < size; ++i) {
snprintf(symbol, symbolSize, "%02X ", ((unsigned char*)data)[i]);
strcat(buffer, symbol);
memset(symbol,0,strlen(symbol));
if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') {
ascii[i % 16] = ((unsigned char*)data)[i];
} else {
ascii[i % 16] = '.';
}
if ((i+1) % 8 == 0 || i+1 == size) {
strcat(buffer, " ");
if ((i+1) % 16 == 0) {
snprintf(symbol, symbolSize, "| %s \n", ascii);
strcat(buffer, symbol);
memset(symbol,0,strlen(symbol));
} else if (i+1 == size) {
ascii[(i+1) % 16] = '\0';
if ((i+1) % 16 <= 8) {
strcat(buffer, " ");
}
for (j = (i+1) % 16; j < 16; ++j) {
strcat(buffer, " ");
}
snprintf(symbol, symbolSize, "| %s \n", ascii);
strcat(buffer, symbol);
memset(symbol,0,strlen(symbol));
}
}
}
free(symbol);
return buffer;
}
@hmtavares
Copy link

Compiled first time with no corrections. Worked perfectly.

Don't forget to free those buffers after you're done folks!

@startergo
Copy link

How did you compile it without main()?

@hmtavares
Copy link

you'll need a main() of some sort. I just added the function to an existing project and it just worked.

@Hermxy
Copy link

Hermxy commented Jan 25, 2023

Thank you so much man👍👍👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment