1 /*
2 * Copyright 2021 Alyssa Rosenzweig
3 * SPDX-License-Identifier: MIT
4 */
5
6 #ifndef U_HEXDUMP_H
7 #define U_HEXDUMP_H
8
9 #include <stdio.h>
10 #include <stdbool.h>
11
12 static inline void
u_hexdump(FILE * fp,const uint8_t * hex,size_t cnt,bool with_strings)13 u_hexdump(FILE *fp, const uint8_t *hex, size_t cnt, bool with_strings)
14 {
15 for (unsigned i = 0; i < cnt; ++i) {
16 if ((i & 0xF) == 0)
17 fprintf(fp, "%06X ", i);
18
19 uint8_t v = hex[i];
20
21 if (v == 0 && (i & 0xF) == 0) {
22 /* Check if we're starting an aligned run of zeroes */
23 unsigned zero_count = 0;
24
25 for (unsigned j = i; j < cnt; ++j) {
26 if (hex[j] == 0)
27 zero_count++;
28 else
29 break;
30 }
31
32 if (zero_count >= 32) {
33 fprintf(fp, "*\n");
34 i += (zero_count & ~0xF) - 1;
35 continue;
36 }
37 }
38
39 fprintf(fp, "%02X ", hex[i]);
40 if ((i & 0xF) == 0xF && with_strings) {
41 fprintf(fp, " | ");
42 for (unsigned j = i & ~0xF; j <= i; ++j) {
43 uint8_t c = hex[j];
44 fputc((c < 32 || c > 128) ? '.' : c, fp);
45 }
46 }
47
48 if ((i & 0xF) == 0xF)
49 fprintf(fp, "\n");
50 }
51
52 fprintf(fp, "\n");
53 }
54
55 #endif
56