Skip to content

Instantly share code, notes, and snippets.

@jpcima
Created August 23, 2022 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpcima/08a5ac3c27aa1935db6cba9f296958cf to your computer and use it in GitHub Desktop.
Save jpcima/08a5ac3c27aa1935db6cba9f296958cf to your computer and use it in GitHub Desktop.
Hexadecimal printing function in the style of xxd
// Copyright Jean Pierre Cimalando 2022.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// SPDX-License-Identifier: BSL-1.0
#include <stdio.h>
#include <stddef.h>
void hexdump(FILE *out, const void *data, size_t len)
{
size_t i = 0;
const char *hex = "0123456789abcdef";
const unsigned char *src = (const unsigned char *)data;
while (i < len) {
size_t n = len - i;
if (n > 16)
n = 16;
if (i > 0)
fputc('\n', out);
fprintf(out, "%08lx:", (unsigned long)i);
for (size_t j = i; j < i + 16; ++j) {
if ((j & 1) == 0)
fputc(' ', out);
if (j < i + n) {
fputc(hex[src[j] >> 4], out);
fputc(hex[src[j] & 15], out);
}
else {
fputc(' ', out);
fputc(' ', out);
}
}
fputc(' ', out);
fputc(' ', out);
for (size_t j = i; j < i + n; ++j) {
unsigned char c = src[j];
fputc((c >= 0x20 && c < 0x80) ? c : '.', out);
}
i += n;
}
fputc('\n', out);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment