-
Notifications
You must be signed in to change notification settings - Fork 0
/
hexdump.hpp
59 lines (52 loc) · 1.32 KB
/
hexdump.hpp
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
#ifndef HEXDUMP_H
#define HEXDUMP_H
#include <iostream>
namespace hex
{
static bool printable(char ch) {
if (ch >= 32 && ch <= 126) {
return true;
}
return false;
}
template<class Elem, class Traits>
inline void dump(const void* aData, std::size_t aLength, std::basic_ostream<Elem, Traits>& aStream, std::size_t aWidth = 16)
{
const char* const start = static_cast<const char*>(aData);
const char* const end = start + aLength;
const char* line = start;
while (line != end)
{
aStream.width(4);
aStream.fill('0');
aStream << std::hex << line - start << " : ";
std::size_t lineLength = std::min(aWidth, static_cast<std::size_t>(end - line));
for (std::size_t pass = 1; pass <= 2; ++pass)
{
for (const char* next = line; next != end && next != line + aWidth; ++next)
{
char ch = *next;
switch(pass)
{
case 1:
aStream << (printable(ch) ? ch : '.');
break;
case 2:
if (next != line)
aStream << " ";
aStream.width(2);
aStream.fill('0');
aStream << std::hex << static_cast<int>(static_cast<unsigned char>(ch));
break;
}
}
if (pass == 1 && lineLength != aWidth)
aStream << std::string(aWidth - lineLength, ' ');
aStream << " ";
}
aStream << std::endl;
line = line + lineLength;
}
}
}
#endif