/* The MIT License (MIT) Copyright © 2020-2025 pacman64 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* You can build this command-line app by running cc -Wall -s -O3 -march=native -mtune=native -flto -o ./nh ./nh.c Building with COMPACT_OUTPUT defined makes `nh` output many fewer bytes, at the cost of using arguably worse colors. You can do that by running cc -s -O3 -march=native -mtune=native -flto -D COMPACT_OUTPUT -o ./nh ./nh.c Building for macos always uses COMPACT_OUTPUT, as the default terminal app there still doesn't support rgb colors. */ #include #include #include #include #include #ifdef _WIN32 #include #include #endif #ifdef RED_ERRORS #define ERROR_STYLE "\x1b[38;2;204;0;0m" #ifdef __APPLE__ #define ERROR_STYLE "\x1b[31m" #endif #define RESET_STYLE "\x1b[0m" #else #define ERROR_STYLE #define RESET_STYLE #endif #ifdef __APPLE__ #define COMPACT_OUTPUT #endif #define ERROR_LINE(MSG) (ERROR_STYLE MSG RESET_STYLE "\n") #ifndef IBUF_SIZE #define IBUF_SIZE (32 * 1024) #endif // EMIT_CONST emits string constants without their final null byte #define EMIT_CONST(w, x) fwrite(x, 1, sizeof(x) - 1, w) const char* info = "" "nh [options...] [filenames...]\n" "\n" "Nice Hexadecimal is a simple hexadecimal (base-16) viewer to inspect bytes\n" "from files or standard input.\n" "\n" "Each line shows the starting offset for the bytes shown, 16 of the bytes\n" "themselves in base-16 notation, and any ASCII codes when the byte values\n" "are in the typical ASCII range.\n" "\n" "The base-16 codes are color-coded, with most bytes shown in gray, while\n" "all-1 and all-0 bytes are shown in orange and blue respectively.\n" "\n" "All-0 bytes are the commonest kind in most binary file types and, along\n" "with all-1 bytes are also a special case worth noticing when exploring\n" "binary data, so it makes sense for them to stand out right away.\n" "\n" "\n" "Options\n" "\n" " -h, --h show this help message\n" " -help, --help aliases for option -h\n" "\n" " -p, --p plain-text output, without ANSI styles\n" " -plain, --plain aliases for option -p\n" "\n" " -do, --do show decimal (base-10) offsets, instead of hex ones\n" " -dec, --dec aliases for option -do\n" " -ho, --ho show hex (base-16) offsets, instead of base-10 ones\n" " -hex, --hex aliases for option -ho\n" ""; #ifdef COMPACT_OUTPUT // #define OUTPUT_FOR_00 "\x1b[38;5;111m00 " // #define OUTPUT_FOR_FF "\x1b[38;5;209mff " // #define NORMAL_HEX_STYLE "\x1b[38;5;246m" // #define ASCII_HEX_STYLE "\x1b[38;5;72m" // #define ASCII_BYTE_STYLE "\x1b[38;5;239m" #define OUTPUT_FOR_00 "\x1b[34m00 " #define OUTPUT_FOR_FF "\x1b[33mff " // #define NORMAL_HEX_STYLE "\x1b[37m" #define NORMAL_HEX_STYLE "\x1b[38;5;246m" #define ASCII_HEX_STYLE "\x1b[32m" #define ASCII_BYTE_STYLE "\x1b[30m" #define ASCII_WS_STYLE "\x1b[36m" #else #define OUTPUT_FOR_00 "\x1b[38;2;135;175;255m00 " #define OUTPUT_FOR_FF "\x1b[38;2;255;135;95mff " #define NORMAL_HEX_STYLE "\x1b[38;2;148;148;148m" #define ASCII_HEX_STYLE "\x1b[38;2;102;175;135m" #define ASCII_BYTE_STYLE "\x1b[38;2;78;78;78m" #define ASCII_WS_STYLE "\x1b[38;2;6;152;154m" #endif // write_hex is faster than calling fprintf(w, "%02x", b): this matters // because it's called for every input byte static inline void write_hex(FILE* w, unsigned char b) { const char* hex_digits = "0123456789abcdef"; fputc(hex_digits[b >> 4], w); fputc(hex_digits[b & 0x0f], w); } // write_styled_hex emits an ANSI color-coded hexadecimal representation of // the byte given; the int given/returned is to keep track of the type of // color-coding used in the previous call, to save some output bytes when // emitting multiple same-styled bytes in sequence, in case the specific // same-styled run allows it static inline int write_styled_hex(FILE* w, unsigned char b, int prev) { // regular ASCII display symbols if (33 <= b && b <= 126) { EMIT_CONST(w, ASCII_HEX_STYLE); write_hex(w, b); EMIT_CONST(w, ASCII_BYTE_STYLE); fputc(b, w); return -1; } // all-bits-off is almost always noteworthy if (b == 0) { if (prev != 0) { EMIT_CONST(w, OUTPUT_FOR_00); } else { EMIT_CONST(w, "00 "); } return 0; } // all-bits-on is often noteworthy if (b == 0xff) { if (prev != 255) { EMIT_CONST(w, OUTPUT_FOR_FF); } else { EMIT_CONST(w, "ff "); } return 255; } // ASCII whitespace if (b == ' ' || b == '\n' || b == '\t' || b == '\r') { EMIT_CONST(w, ASCII_WS_STYLE); write_hex(w, b); EMIT_CONST(w, ASCII_BYTE_STYLE " "); return -1; } // ASCII control values, and other bytes beyond displayable ASCII if (prev != 10) { EMIT_CONST(w, NORMAL_HEX_STYLE); } write_hex(w, b); fputc(' ', w); return 10; } // ruler emits a ruler-like string of spaced-out symbols static inline void ruler(FILE* w, size_t bytes_per_line) { const size_t gap = 4; if (bytes_per_line < gap) { return; } EMIT_CONST(w, " ·"); for (size_t n = bytes_per_line - gap; n >= gap; n -= gap) { EMIT_CONST(w, " ·"); } } // write_commas_uint shows a number by separating 3-digits groups with commas void write_commas_uint(FILE* w, size_t n) { if (n == 0) { EMIT_CONST(w, "0"); return; } size_t digits; // 20 is the most digits unsigned 64-bit ints can ever need unsigned char buf[24]; for (digits = 0; n > 0; digits++, n /= 10) { buf[sizeof(buf) - 1 - digits] = (n % 10) + '0'; } // now emit the leading digits, which may not come in 3 size_t leading = digits % 3; if (leading == 0) { // avoid having a comma before the first digit leading = digits < 3 ? digits : 3; } unsigned char* start = buf + sizeof(buf) - digits; fwrite(start, 1, leading, w); start += leading; digits -= leading; // now emit all remaining digits in groups of 3, alternating styles for (; digits > 0; start += 3, digits -= 3) { fputc(',', w); fwrite(start, 1, 3, w); } } // output_state ties all values representing the current state shared across // all functions involved in interpreting the input-buffer and showing its // bytes and ASCII values typedef struct output_state { // the whole input-buffer and its currently-used length in bytes unsigned char* buf; size_t buflen; // the ASCII-text buffer and its currently-used length in bytes unsigned char* txt; size_t txtlen; // offset is the byte counter, shown at the start of each line size_t offset; // line_width is how many bytes each line can show at most size_t line_width; // lines is the line counter, which is used to provide periodic // breather lines, to make eye-scanning big output blobs easier size_t lines; // emit_offset is chosen to emit the offset at the start of each line void (*emit_offset)(FILE* w, size_t offset); // showtxt is a hint on whether it's sensible to show the ASCII-text // buffer for the current line bool showtxt; } output_state; // peek_ascii looks 2 lines ahead in the buffer to get all ASCII-like runs // of bytes, which are later meant to show on the side panel void peek_ascii(size_t i, size_t end, output_state* os) { os->txtlen = 0; os->showtxt = false; for (size_t j = i; j < end; j++) { const unsigned char b = os->buf[j]; const bool is_vis_ascii = ' ' <= b && b <= '~'; os->showtxt = os->showtxt | is_vis_ascii; os->txt[os->txtlen] = is_vis_ascii ? b : ' '; os->txtlen++; } // keep trailing spaces in the ASCII viewer, since real ASCII streaks // can have them: an example is the `WAVEfmt ` header in .wav files // while (os->txtlen > 0 && os->txt[os->txtlen - 1] == ' ') { // os->txtlen--; // } } // write_plain_uint is the unstyled counterpart of func write_styled_uint void write_plain_uint(FILE* w, size_t n) { if (n < 1) { EMIT_CONST(w, " 0"); return; } size_t digits; // 20 is the most digits unsigned 64-bit ints can ever need unsigned char buf[24]; for (digits = 0; n > 0; digits++, n /= 10) { buf[sizeof(buf) - 1 - digits] = (n % 10) + '0'; } // left-pad the coming digits up to 8 chars if (digits < 8) { fwrite((unsigned char*)" ", 1, 8 - digits, w); } // emit all digits const unsigned char* start = buf + sizeof(buf) - digits; fwrite(start, 1, digits, w); } void write_hex_uint(FILE* w, size_t n) { if (n < 1) { EMIT_CONST(w, "00000000"); return; } size_t digits; // 20 is the most digits unsigned 64-bit ints can ever need unsigned char buf[24]; for (digits = 0; n > 0; digits += 2, n /= 256) { unsigned char b = n % 256; const char* hex_digits = "0123456789abcdef"; buf[sizeof(buf) - 1 - digits - 1] = hex_digits[b >> 4]; buf[sizeof(buf) - 1 - digits - 0] = hex_digits[b & 0x0f]; } // left-pad the coming digits up to 8 chars if (digits < 8) { fwrite((unsigned char*)"00000000", 1, 8 - digits, w); } // emit all digits const unsigned char* start = buf + sizeof(buf) - digits; fwrite(start, 1, digits, w); } // write_styled_uint is a quick way to emit the offset-counter showing at the // start of each line; it assumes 8-item left-padding of values, unless the // numbers are too big for that void write_styled_uint(FILE* w, size_t n) { if (n < 1) { EMIT_CONST(w, " 0"); return; } size_t digits; // 20 is the most digits unsigned 64-bit ints can ever need unsigned char buf[24]; for (digits = 0; n > 0; digits++, n /= 10) { buf[sizeof(buf) - 1 - digits] = (n % 10) + '0'; } // left-pad the coming digits up to 8 chars if (digits < 8) { fwrite((unsigned char*)" ", 1, 8 - digits, w); } // now emit the leading digits, which may be fewer than 3 size_t leading = digits % 3; unsigned char* start = buf + sizeof(buf) - digits; fwrite(start, 1, leading, w); start += leading; digits -= leading; // now emit all remaining digits in groups of 3, alternating styles bool styled = leading != 0; for (; digits > 0; start += 3, digits -= 3, styled = !styled) { if (styled) { #ifdef COMPACT_OUTPUT EMIT_CONST(w, "\x1b[38;5;248m"); #else EMIT_CONST(w, "\x1b[38;2;168;168;168m"); #endif fwrite(start, 1, 3, w); EMIT_CONST(w, "\x1b[0m"); } else { fwrite(start, 1, 3, w); } } } // emit_styled_file_info emits an ANSI-styled line showing a filename and the // file's size in bytes void emit_styled_file_info(FILE* w, const char* path, size_t nbytes) { EMIT_CONST(w, "• "); fwrite((unsigned char*)path, 1, strlen(path), w); #ifdef COMPACT_OUTPUT EMIT_CONST(w, " \x1b[38;5;245m("); #else EMIT_CONST(w, " \x1b[38;2;138;138;138m("); #endif write_commas_uint(w, nbytes); EMIT_CONST(w, " bytes)\x1b[0m\n"); } // emit_plain_file_info is the unstyled counterpart of func emit_styled_file_info void emit_plain_file_info(FILE* w, const char* path, size_t nbytes) { EMIT_CONST(w, "• "); fwrite((unsigned char*)path, 1, strlen(path), w); EMIT_CONST(w, " ("); write_commas_uint(w, nbytes); EMIT_CONST(w, " bytes)\n"); } // emit_styled_line handles the details of showing a styled line out of the // current input-buffer chunk void emit_styled_line(FILE* w, size_t i, size_t end, output_state* os) { int prev_type = -1; for (size_t j = i; j < end; j++, os->offset++) { const unsigned char b = os->buf[j]; if (j % os->line_width == 0) { // show a ruler every few lines to make eye-scanning easier if (os->lines % 5 == 0 && os->lines > 0) { #ifdef COMPACT_OUTPUT EMIT_CONST(w, " \x1b[38;5;245m"); #else EMIT_CONST(w, " \x1b[38;2;138;138;138m"); #endif ruler(w, os->line_width); EMIT_CONST(w, "\x1b[0m\n"); } os->lines++; prev_type = -1; // reset previous-style, since it's a new line // start next line with offset of its 1st item, also changing the // background color for the colored hex code which will follow // fprintf(stdout, "%8d", os->offset); os->emit_offset(w, os->offset); #ifdef COMPACT_OUTPUT EMIT_CONST(w, " \x1b[48;5;254m"); #else EMIT_CONST(w, " \x1b[48;2;228;228;228m"); #endif } // show the current byte `with style` prev_type = write_styled_hex(w, b, prev_type); } if (os->showtxt) { EMIT_CONST(w, "\x1b[0m "); for (size_t j = end - i; j < os->line_width; j++) { EMIT_CONST(w, " "); } fwrite(os->txt, 1, os->txtlen, w); fputc('\n', w); return; } EMIT_CONST(w, "\x1b[0m\n"); } // emit_plain_line handles the details of showing a plain (unstyled) line out // of the current input-buffer chunk void emit_plain_line(FILE* w, size_t i, size_t end, output_state* os) { for (size_t j = i; j < end; j++, os->offset++) { const unsigned char b = os->buf[j]; if (j % os->line_width == 0) { // show a ruler every few lines to make eye-scanning easier if (os->lines % 5 == 0 && os->lines > 0) { fputc('\n', w); } os->lines++; os->emit_offset(w, os->offset); // start next line with offset of its 1st item, also // changing the background color for the colored hex // code which will follow // fprintf(stdout, "%8d", os->offset); EMIT_CONST(w, " "); } // show the current byte unstyled write_hex(w, b); fputc(' ', w); } if (os->showtxt) { EMIT_CONST(w, " "); for (size_t j = end - i; j < os->line_width; j++) { EMIT_CONST(w, " "); } fwrite(os->txt, 1, os->txtlen, w); fputc('\n', w); return; } fputc('\n', w); } // config has all the settings used to emit output typedef struct config { // bytes_per_line determines the `width` of output lines size_t bytes_per_line; // emit_file_info is chosen to emit file-info with colors or plainly void (*emit_file_info)(FILE* w, const char* path, size_t nbytes); // emit_line is chosen to emit hex bytes with colors or plainly void (*emit_line)(FILE* w, size_t i, size_t end, output_state* os); // emit_offset is chosen to emit the offset at the start of each line void (*emit_offset)(FILE* w, size_t offset); } config; // handle_reader shows all bytes read from the source given as colored hex // values, showing offsets and ASCII symbols on the sides of each output line void handle_reader(FILE* w, FILE* src, config cfg) { // limit line-width to the buffer's capacity if (cfg.bytes_per_line > IBUF_SIZE) { cfg.bytes_per_line = IBUF_SIZE; } const size_t two_lines = 2 * cfg.bytes_per_line; unsigned char txt[two_lines]; unsigned char buf[IBUF_SIZE]; // ensure the effective buffer-size is a multiple of the line-width size_t max = sizeof(buf) - sizeof(buf) % cfg.bytes_per_line; output_state os; os.buf = buf; os.line_width = cfg.bytes_per_line; os.lines = 0; os.offset = 0; os.txt = txt; os.emit_offset = cfg.emit_offset; os.showtxt = true; const size_t one_line = cfg.bytes_per_line; while (!feof(w)) { os.buflen = fread(&buf, sizeof(buf[0]), max, src); if (os.buflen < 1) { // assume input is over when no bytes were read break; } for (size_t i = 0; i < os.buflen; i += one_line) { size_t end; // remember all ASCII symbols in current pair of output lines end = i + two_lines < os.buflen ? i + two_lines : os.buflen; peek_ascii(i, end, &os); // show current output line end = i + one_line < os.buflen ? i + one_line : os.buflen; cfg.emit_line(w, i, end, &os); } } fflush(w); } // handle_file handles data from the filename given; returns false only when // the file can't be opened bool handle_file(FILE* w, const char* path, config cfg) { FILE* f = fopen(path, "rb"); if (f == NULL) { fputc('\n', w); fprintf(stderr, ERROR_LINE("can't open file named '%s'"), path); return false; } // get the file size struct stat st; fstat(fileno(f), &st); // show output cfg.emit_file_info(w, path, st.st_size); fputc('\n', w); handle_reader(w, f, cfg); fclose(f); return true; } // is_help_option simplifies control-flow for func run bool is_help_option(const char* s) { return (s[0] == '-') && ( strcmp(s, "-h") == 0 || strcmp(s, "-help") == 0 || strcmp(s, "--h") == 0 || strcmp(s, "--help") == 0 ); } // is_plain_option simplifies control-flow for func run bool is_plain_option(const char* s) { return (s[0] == '-') && ( strcmp(s, "-p") == 0 || strcmp(s, "--p") == 0 || strcmp(s, "-plain") == 0 || strcmp(s, "--plain") == 0 ); } // is_hex_offsets simplifies control-flow for func run bool is_hex_offsets_option(const char* s) { return (s[0] == '-') && ( strcmp(s, "-ho") == 0 || strcmp(s, "--ho") == 0 || strcmp(s, "-hex") == 0 || strcmp(s, "--hex") == 0 || strcmp(s, "-hexoffsets") == 0 || strcmp(s, "--hexoffsets") == 0 || strcmp(s, "-hex-offsets") == 0 || strcmp(s, "--hex-offsets") == 0 ); } // is_dec_offsets simplifies control-flow for func run bool is_dec_offsets_option(const char* s) { return (s[0] == '-') && ( strcmp(s, "-do") == 0 || strcmp(s, "--do") == 0 || strcmp(s, "-dec") == 0 || strcmp(s, "--dec") == 0 || strcmp(s, "-decoffsets") == 0 || strcmp(s, "--decoffsets") == 0 || strcmp(s, "-dec-offsets") == 0 || strcmp(s, "--dec-offsets") == 0 ); } // run returns the number of errors int run(int argc, char** argv, FILE* w) { config cfg; cfg.bytes_per_line = 16; cfg.emit_line = &emit_styled_line; cfg.emit_file_info = &emit_styled_file_info; cfg.emit_offset = &write_styled_uint; size_t files = 0; size_t errors = 0; // handle all filenames/options given for (size_t i = 1; i < argc && !feof(w); i++) { // a `-` filename stands for the standard input if (argv[i][0] == '-' && argv[i][1] == 0) { EMIT_CONST(w, "• \n"); EMIT_CONST(w, "\n"); handle_reader(w, stdin, cfg); continue; } if (is_plain_option(argv[i])) { cfg.emit_line = &emit_plain_line; cfg.emit_file_info = &emit_plain_file_info; // hex offsets are already plain if (cfg.emit_offset != &write_hex_uint) { cfg.emit_offset = &write_plain_uint; } continue; } if (is_hex_offsets_option(argv[i])) { cfg.emit_offset = &write_hex_uint; continue; } if (is_dec_offsets_option(argv[i])) { // keep plain decimal offsets that way if (cfg.emit_offset != &write_plain_uint) { cfg.emit_offset = &write_styled_uint; } continue; } if (files > 0) { // put an empty line between adjacent hex outputs fputc('\n', w); } if (!handle_file(w, argv[i], cfg)) { errors++; } files++; } // no filenames means use stdin as the only input if (files == 0) { EMIT_CONST(w, "• \n"); EMIT_CONST(w, "\n"); handle_reader(w, stdin, cfg); } return errors; } int main(int argc, char** argv) { #ifdef _WIN32 setmode(fileno(stdin), O_BINARY); // ensure output lines end in LF instead of CRLF on windows setmode(fileno(stdout), O_BINARY); setmode(fileno(stderr), O_BINARY); #endif if (argc > 1 && is_help_option(argv[1])) { fprintf(stderr, "%s", info); return 0; } // enable full buffering for stdout setvbuf(stdout, NULL, _IOFBF, 0); return run(argc, argv, stdout) == 0 ? 0 : 1; }