Amit Pundir | 33109f7 | 2020-02-07 22:26:08 +0530 | [diff] [blame] | 1 | #include <ctype.h> |
| 2 | #include <stdint.h> |
| 3 | #include <stdio.h> |
| 4 | #include "util.h" |
| 5 | |
| 6 | static uint8_t to_hex(uint8_t ch) |
| 7 | { |
| 8 | ch &= 0xf; |
| 9 | return ch <= 9 ? '0' + ch : 'a' + ch - 10; |
| 10 | } |
| 11 | |
| 12 | void print_hex_dump(const char *prefix, const void *buf, size_t len) |
| 13 | { |
| 14 | const uint8_t *ptr = buf; |
| 15 | size_t linelen; |
| 16 | uint8_t ch; |
| 17 | char line[16 * 3 + 16 + 1]; |
| 18 | int li; |
| 19 | int i; |
| 20 | int j; |
| 21 | |
| 22 | for (i = 0; i < len; i += 16) { |
| 23 | linelen = MIN(16, len - i); |
| 24 | li = 0; |
| 25 | |
| 26 | for (j = 0; j < linelen; j++) { |
| 27 | ch = ptr[i + j]; |
| 28 | line[li++] = to_hex(ch >> 4); |
| 29 | line[li++] = to_hex(ch); |
| 30 | line[li++] = ' '; |
| 31 | } |
| 32 | |
| 33 | for (; j < 16; j++) { |
| 34 | line[li++] = ' '; |
| 35 | line[li++] = ' '; |
| 36 | line[li++] = ' '; |
| 37 | } |
| 38 | |
| 39 | for (j = 0; j < linelen; j++) { |
| 40 | ch = ptr[i + j]; |
| 41 | line[li++] = isprint(ch) ? ch : '.'; |
| 42 | } |
| 43 | |
| 44 | line[li] = '\0'; |
| 45 | |
| 46 | printf("%s %04x: %s\n", prefix, i, line); |
| 47 | } |
| 48 | } |