46 lines
1.4 KiB
C
46 lines
1.4 KiB
C
//
|
|
// Created by bruno on 6.2.2025.
|
|
//
|
|
|
|
#include "hexdump.h"
|
|
#include <stdio.h>
|
|
#include <ctype.h>
|
|
#include <malloc.h>
|
|
#include <stdint.h>
|
|
#include <string.h>
|
|
|
|
#define BYTES_PER_LINE 16 // Adjust for different widths
|
|
|
|
|
|
char *hexdump_to_string(const unsigned char *data, uint32_t start, uint32_t end) {
|
|
if (start >= end) return NULL; // Invalid range
|
|
|
|
// Estimate max output size: each line is approx. 80 chars
|
|
uint32_t estimated_size = ((end - start) / BYTES_PER_LINE + 1) * 60;
|
|
|
|
// Allocate memory for output string
|
|
char *output = malloc(estimated_size);
|
|
if (!output) return NULL;
|
|
|
|
uint32_t out_offset = 0; // Tracks position in output buffer
|
|
|
|
for (uint32_t i = start; i < end; i += BYTES_PER_LINE) {
|
|
// Print offset
|
|
out_offset += snprintf(output + out_offset, estimated_size - out_offset, "%07x ", i);
|
|
|
|
// Print hex values
|
|
for (uint32_t j = 0; j < BYTES_PER_LINE; j++) {
|
|
if (i + j < end)
|
|
out_offset += snprintf(output + out_offset, estimated_size - out_offset, "%02x ", data[i + j]);
|
|
else
|
|
out_offset += snprintf(output + out_offset, estimated_size - out_offset, " "); // Padding
|
|
if (j == 7)
|
|
out_offset += snprintf(output + out_offset, estimated_size - out_offset, " "); // Extra space
|
|
}
|
|
|
|
out_offset += snprintf(output + out_offset, estimated_size - out_offset, "\n");
|
|
}
|
|
|
|
return output;
|
|
}
|