-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.cpp
100 lines (85 loc) · 2.21 KB
/
utils.cpp
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "utils.h"
#include <cstdint>
#include <fstream>
#include <iostream>
namespace util {
std::vector<uint8_t> readFile(const std::string_view &filename) {
std::ifstream fs(filename.data(), std::ios::binary);
std::vector<uint8_t> res(std::istreambuf_iterator<char>(fs), {});
return res;
}
void printfBits(std::string msg, int n, int bits, bool newline) {
printf("%s", msg.c_str());
for (int b = bits - 1; b >= 0; b--) {
if (b != (bits - 1) && b % 4 == 3)
printf(" ");
printf("%d", (n & (1 << b)) ? 1 : 0);
}
if (newline)
printf("\n");
}
void hexdump(std::vector<uint8_t> hex) {
hexdump(hex, hex.size(), 0);
}
void hexdump(std::vector<uint8_t> hex, size_t length) {
hexdump(hex, length, 0);
}
void hexdump(std::vector<uint8_t> hex, size_t length, size_t base) {
std::string charview;
bool wasCopy = false;
int c = 0;
for (; c < hex.size() && c < length;) {
if (c % 16 == 0) {
bool isCopy = false;
if (c >= 16 && hex.size() - c >= 16) {
isCopy = true;
for (int col = 0; col < 16; col++)
if (hex[c + col] != hex[c + col - 16])
isCopy = false;
if (isCopy) {
bool isAdditionalCopy = false;
if (c >= 32 && hex.size() - c >= 16) {
isAdditionalCopy = true;
for (int col = 0; col < 16; col++)
if (hex[c + col] != hex[c + col - 32])
isAdditionalCopy = false;
}
if (!isAdditionalCopy)
printf("*\n");
wasCopy = true;
c += 16;
continue;
}
}
}
wasCopy = false;
int b = hex[c];
if (c % 16 == 0)
printf("%08lx: ", base + c);
printf("%02x ", b);
if (std::isprint(b))
charview += b;
else
charview += '.';
c++;
if (c % 8 == 0)
std::cout << " ";
if (c % 16 == 0) {
std::cout << "|" << charview << "|" << std::endl;
charview = "";
}
}
if (c % 16 != 0) {
while (c % 16 != 0) {
std::cout << " ";
c++;
if (c % 8 == 0)
std::cout << " ";
if (c % 16 == 0)
std::cout << "|" << charview << "|" << std::endl;
}
}
if (wasCopy)
printf("%08lx:\n", base + c);
}
} // namespace util