-
Notifications
You must be signed in to change notification settings - Fork 0
/
hexchk.c
76 lines (58 loc) · 2.03 KB
/
hexchk.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// hexchk.c - the same as src/hexchk.rs, with the same logic, but written in C
// for comparison purposes.
// also some changes have been made, to reduce total number of instructions generated by the compiler (such as omitting the mask, or following sketchy practices like using a fixed size buffer for the color string, etc.)
#include <stdio.h>
typedef unsigned char uint8_t;
char * hex_to_color(uint8_t hex, uint8_t min, uint8_t max) {
if (hex < min || hex > max) {
return "\x1b[0m";
}
int rgb = hex * (16581375 / (max - min));
uint8_t r = (rgb >> 16); // we can omit the mask here, since we know the value is in the range
uint8_t g = (rgb >> 8);
uint8_t b = rgb;
char color[16];
sprintf(color, "\x1b[38;2;%d;%d;%dm", r, g, b);
return color;
}
int main(int argc, char ** argv) {
FILE * fp = fopen(argc > 1 ? argv[1] : "/dev/stdin", "r");
if (!fp) {
printf("Error:fopen\n");
return 1;
}
uint8_t mode = argc > 2 ? 0 : 1;
uint8_t buffer[16];
int offset = 0;
while (1) {
size_t bytes_read = fread(buffer, 1u, 16u, fp);
if (bytes_read == 0) {
break;
} else if (bytes_read > 0) {
printf("%08x ", offset);
offset += bytes_read;
for (uint8_t i = 0; i < 16; i++) {
if (i < bytes_read) {
printf("%s%02x ", mode?"":hex_to_color(buffer[i], 0x20, 0x7e), buffer[i]);
} else {
printf(" ");
}
}
printf(" \x1b[0m|");
uint8_t c;
for (uint8_t i = 0; i < 16; i++) {
if (i < bytes_read) {
c = buffer[i];
printf("%s%c", mode?"":hex_to_color(buffer[i], 0x20u, 0x7eu), c>=0x20u&&c<=0x7eu?c:'.');
} else {
printf(" ");
}
}
printf("\x1b[0m|\n");
} else {
printf("Error:fread\n");
return 1;
}
}
fclose(fp);
}