Last active
July 25, 2022 09:20
-
-
Save shawnfeng0/df748a75d4b451673939afc3df094c6c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ctype.h> | |
#include <inttypes.h> | |
#include <stdio.h> | |
#include <string.h> | |
uintptr_t HexDumpData(const uint8_t *data, size_t length, size_t width = 16, | |
uintptr_t base_address = 0, bool tail_addr_out = true) { | |
const uint8_t *data_cur = data; | |
if (!data || width == 0) return 0; | |
while (length) { | |
printf("%08" PRIxPTR " ", data_cur - data + base_address); | |
for (size_t i = 0; i < width; i++) { | |
if (i < length) | |
printf("%02" PRIx8 " %s", data_cur[i], i == width / 2 - 1 ? " " : ""); | |
else | |
printf(" %s", i == width / 2 - 1 ? " " : ""); | |
} | |
printf(" |"); | |
for (size_t i = 0; i < width && i < length; i++) | |
printf("%c", isprint(data_cur[i]) ? data_cur[i] : '.'); | |
printf("|\n"); | |
data_cur += length < width ? length : width; | |
length -= length < width ? length : width; | |
} | |
if (tail_addr_out) printf("%08" PRIxPTR "\n", data_cur - data + base_address); | |
return data_cur - data + base_address; | |
} | |
uintptr_t HexDumpFile(FILE *file, size_t width) { | |
if (!file) return 0; | |
uint8_t buffer[width]; | |
uintptr_t cur_address = 0; | |
while (size_t count = fread(buffer, 1, sizeof(buffer), file)) { | |
cur_address = | |
HexDumpData(buffer, count, width, cur_address, count != width); | |
} | |
if (width == 1) HexDumpData(buffer, 0, width, cur_address, true); | |
return cur_address; | |
} | |
int main(int argc, char *argv[]) { | |
char filename[FILENAME_MAX]; // C's max length of file name. | |
FILE *file = nullptr; | |
if (argc == 1) { | |
printf( | |
"Please tell me your file name(with path if not in the current " | |
"dir):\n"); | |
scanf("%s", filename); | |
} else { | |
strcpy(filename, argv[1]); | |
} | |
file = fopen(filename, "rb"); | |
if (file == nullptr) { | |
printf("Can't access %s!\n", filename); | |
return 0; | |
} | |
HexDumpFile(file, 16); | |
fclose(file); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment