ratazana/hexdump.h
2025-11-10 04:53:37 -03:00

53 lines
1.1 KiB
C

/**
* Copyright (c) 2025 favewa
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
typedef enum {
HEXDUMP_COMPACT,
HEXDUMP_DETAILED,
} hexdump_style;
static constexpr size_t BYTES_PER_LINE = 16;
static constexpr int ADDR_WIDTH = (int)(sizeof(size_t) * 2);
void hexdump(const char *restrict prefix, const uint8_t data[static 1],
size_t len, hexdump_style style)
{
if (style == HEXDUMP_COMPACT) {
if (prefix)
printf("%s (%zu bytes): ", prefix, len);
for (size_t i = 0; i < len; i++) {
printf("%02X ", data[i]);
}
printf("\n");
return;
}
if (prefix)
printf("%s (%zu bytes):\n", prefix, len);
for (size_t i = 0; i < len; i += BYTES_PER_LINE) {
printf(" %0*zx ", ADDR_WIDTH, i);
for (size_t j = 0; j < BYTES_PER_LINE; j++) {
i + j < len ? printf("%02X ", data[i + j]) : printf(" ");
if (j == 7)
printf(" ");
}
printf(" |");
for (size_t j = 0; j < BYTES_PER_LINE && i + j < len; j++) {
uint8_t c = data[i + j];
printf("%c", (c >= 32 && c < 127) ? c : '.');
}
printf("|\n");
}
}