0%

仿Hexdump的实现

编码过程中我们有时候需要将数据的十六进制值打出来看看,这里做一下记录

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
101
102
103
104
105
106
107
108
109
110
#include <ctype.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include <iomanip>

std::string pretty_string(uint8_t* ret,size_t size)
{
if(size == 0)
{
return "";
}
std::stringstream out;
for (size_t i = 0; i < size; i++)
{
size_t c = i;
out << std::hex << std::setw(2*sizeof(size_t)) << std::setfill('0') << i << " ";
for (size_t j = 0; j < 8; j++, c++)
{
if (c < size)
{
// printf("%02X ", ret[c]);
out << std::hex << std::setw(2) << std::setfill('0') << (int)ret[c] << " ";
}
else
{
out << " ";
}
}
out << " ";
for (size_t j = 0; j < 8; j++, c++)
{
if (c < size)
{
out << std::hex << std::setw(2) << std::setfill('0') << (int)ret[c] << " ";
}
else
{
out << " ";
}
}
c = i;
out << " |";
size_t count = 0;
for (size_t j = 0; j < 16 && c < size; j++, c++, count++)
{
if (isprint(ret[c]) && ret[c])
{
out << (char)ret[c];
}
else
{
out << ".";
}
}
i = i + count - 1;
out <<"|\n";
}
out << std::hex << std::setw(2*sizeof(size_t)) << std::setfill('0') << size << std::endl;
return out.str();
}

void pretty_print(uint8_t* ret,size_t size)
{
for (size_t i = 0; i < size; i++)
{
size_t c = i;
printf("%0.*zx ",(int)sizeof(size_t)*2,i);
for (size_t j = 0; j < 8; j++, c++)
{
if (c < size)
{
printf("%02X ", ret[c]);
}
else
{
printf(" ");
}
}
printf(" ");
for (size_t j = 0; j < 8; j++, c++)
{
if (c < size)
{
printf("%02X ", ret[c]);
}
else
{
printf(" ");
}
}
c = i;
printf(" |");
size_t count = 0;
for (size_t j = 0; j < 16 && c < size; j++, c++, count++)
{
if (isprint(ret[c]) && ret[c])
{
printf("%c", ret[c]);
}
else
{
printf(".");
}
}
i = i + count - 1;
printf("|\n");
}
printf("%0.*zx\n",(int)sizeof(size_t)*2,size);
}