-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathHexData.cpp
More file actions
74 lines (60 loc) · 1.43 KB
/
HexData.cpp
File metadata and controls
74 lines (60 loc) · 1.43 KB
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
#include "HexData.h"
#include <sstream>
#include <stdexcept>
using namespace std;
using namespace opendnp3;
HexData::HexData(const std::string& hex, bool allowBadChars)
: HexData(RemoveBadCharacters(hex, allowBadChars))
{
}
HexData::HexData(const std::string& valid) : m_buffer()
{
auto NUM_BYTES = valid.size()/2;
for(size_t pos = 0; pos < NUM_BYTES; ++pos)
{
uint32_t val;
std::stringstream ss;
ss << std::hex << valid.substr(2*pos, 2);
if((ss >> val).fail())
{
throw std::invalid_argument("failed to convert hex");
}
m_buffer[pos] = static_cast<uint8_t>(val);
}
}
opendnp3::Buffer HexData::GetSlice() const
{
return Buffer(m_buffer.data(), m_buffer.size());
}
std::string HexData::RemoveBadCharacters(const std::string& hex, bool allowBadChars)
{
ostringstream oss;
for(const char& c : hex)
{
if(IsHexChar(c))
{
oss << c;
}
else if(c != ' ' && !allowBadChars)
{
throw std::invalid_argument("Bad character");
}
}
return oss.str();
}
bool HexData::IsHexChar(char i)
{
return IsDigit(i) || IsUpperHexAlpha(i) || IsLowerHexAlpha(i);
}
bool HexData::IsDigit(char i)
{
return (i >= '0') && (i <= '9');
}
bool HexData::IsUpperHexAlpha(char i)
{
return (i >= 'A') && (i <= 'F');
}
bool HexData::IsLowerHexAlpha(char i)
{
return (i >= 'a') && (i <= 'f');
}