Files
RISC-B/util/hexdump.c

51 lines
1.7 KiB
C

//
// Created by bruno on 6.2.2025.
//
#include "hexdump.h"
#include <stdio.h>
#include <ctype.h>
#include <malloc.h>
#define BYTES_PER_LINE 16 // Adjust for different widths
char *hexdump_to_string(const unsigned char *data, size_t size) {
// Estimate max output size: each line is approx. 80 chars
size_t estimated_size = (size / BYTES_PER_LINE + 1) * 80;
// Allocate memory for output string
char *output = malloc(estimated_size);
if (!output) return NULL;
size_t offset = 0; // Track the write position
for (size_t i = 0; i < size; i += BYTES_PER_LINE) {
offset += snprintf(output + offset, estimated_size - offset, "%08zx ", i);
// Print hex values
for (size_t j = 0; j < BYTES_PER_LINE; j++) {
if (i + j < size)
offset += snprintf(output + offset, estimated_size - offset, "%02x ", data[i + j]);
else
offset += snprintf(output + offset, estimated_size - offset, " "); // Padding
if (j == 7) offset += snprintf(output + offset, estimated_size - offset, " "); // Extra space
}
offset += snprintf(output + offset, estimated_size - offset, " |");
// Print ASCII representation
for (size_t j = 0; j < BYTES_PER_LINE; j++) {
if (i + j < size)
offset += snprintf(output + offset, estimated_size - offset, "%c",
isprint(data[i + j]) ? data[i + j] : '.');
else
offset += snprintf(output + offset, estimated_size - offset, " ");
}
offset += snprintf(output + offset, estimated_size - offset, "|\n");
}
return output;
}