Skip to content

Instantly share code, notes, and snippets.

@ishchegl
Last active April 11, 2017 07:11
Show Gist options
  • Save ishchegl/aea5814e96e329053ef0 to your computer and use it in GitHub Desktop.
Save ishchegl/aea5814e96e329053ef0 to your computer and use it in GitHub Desktop.
Print HEX in C
#include <stdio.h>
#include <string.h>
#define MAX_DATA_LEN 1024
static unsigned char hex_string[MAX_DATA_LEN];
static inline char convert_to_printable(char c)
{
return c < 32 || c > 126 ? '.' : c;
}
static void print_hex(const unsigned char *buf,
int length,
int width,
int error /* void (*printf)(const char *) */)
{
int remainder = length % width;
int whole = length - remainder;
int i = 0;
int j = 0;
int offset = 0;
memset(hex_string, 0, sizeof(hex_string));
if (!error)
fprintf(stdout, "(%p, %d bytes)\n", buf, length);
else
fprintf(stderr, "(%p, %d bytes)\n", buf, length);
for (i = 0; i < whole; i += width)
{
offset = 0;
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, "| 0x%08X | ", i);
for (j = 0; j < width; j++)
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, "%02X ", buf[i + j]);
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, "| ");
for (j = 0; j < width; j++)
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, "%c", convert_to_printable(buf[i + j]));
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, " |");
if (!error)
fprintf(stdout, "%s\n", hex_string);
else
fprintf(stderr, "%s\n", hex_string);
}
if (remainder)
{
offset = 0;
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, "| 0x%08X | ", i);
for (j = 0; j < remainder; j++)
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, "%02X ", buf[whole + j]);
for (j = 0; j < width - remainder; j++)
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, " ");
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, "| ");
for (j = 0; j < remainder; j++)
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, "%c", convert_to_printable(buf[i + j]));
for (j = 0; j < width - remainder; j++)
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, " ");
offset += snprintf((char *)(hex_string + offset), sizeof(hex_string) - offset, " |");
if (!error)
fprintf(stdout, "%s\n", hex_string);
else
fprintf(stderr, "%s\n", hex_string);
}
memset(hex_string, 0, sizeof(hex_string));
}
int main(int argc, char **argv)
{
const char *str = "What is the key to life on Earth?";
print_hex(str, strlen(str), 16, 0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment