25 #ifndef SER4CPP_HEX_CONVERSIONS_H 26 #define SER4CPP_HEX_CONVERSIONS_H 28 #include "ser4cpp/container/SequenceTypes.h" 29 #include "ser4cpp/container/Buffer.h" 41 static char to_hex_char(
char c)
43 return (c > 9) ? (
'A' + (c - 10)) : (
'0' + c);
46 static std::string byte_to_hex(uint8_t b)
48 std::ostringstream oss;
49 oss << HexConversions::to_hex_char((b & 0xf0) >> 4) << HexConversions::to_hex_char(b & 0xf);
53 static std::string to_hex(
const uint8_t* buffer,
size_t length,
bool spaced =
false)
55 std::ostringstream oss;
56 size_t last = length - 1;
57 for (
size_t i = 0; i < length; i++)
60 oss << HexConversions::to_hex_char((c & 0xf0) >> 4) << HexConversions::to_hex_char(c & 0xf);
61 if (spaced && i != last)oss <<
" ";
66 static std::string to_hex(
const rseq_t& buffer,
bool spaced =
true)
68 return to_hex(buffer, buffer.length(), spaced);
71 static std::string append_hex(std::initializer_list<std::string> segments)
73 std::ostringstream oss;
75 for (
auto& str : segments)
80 return to_hex(from_hex(oss.str())->as_rslice());
83 static std::string repeat_hex(uint8_t
byte, uint16_t count,
bool spaced =
true)
86 buffer.as_wslice().set_all_to(
byte);
87 return to_hex(buffer.as_rslice(), spaced);
90 static std::string increment_hex(uint8_t start, uint16_t count,
bool spaced =
true)
94 for (uint16_t i = 0; i < count; ++i)
96 buffer.as_wslice()[i] = start;
100 return to_hex(buffer.as_rslice(), spaced);
103 static std::unique_ptr<Buffer> from_hex(
const std::string& hex)
106 const std::string copy = HexConversions::remove_spaces(hex);
109 if (copy.find_first_of(
"oO") != std::string::npos)
111 throw std::invalid_argument(
"Sequence contains 'o' or 'O'");
114 if (copy.size() % 2 != 0)
116 throw std::invalid_argument(hex);
119 const auto num_bytes = static_cast<uint32_t>(copy.size() / 2);
121 auto buffer = std::make_unique<Buffer>(num_bytes);
123 for (
size_t index = 0, pos = 0; pos < copy.size(); ++index, pos += 2)
126 std::stringstream ss;
127 ss << std::hex << copy.substr(pos, 2);
128 if ((ss >> val).fail())
130 throw std::invalid_argument(hex);
132 buffer->as_wslice()[index] = static_cast<uint8_t>(val);
135 return std::move(buffer);
139 static void remove_spaces_in_place(std::string& hex)
141 size_t pos = hex.find_first_of(
' ');
142 if (pos != std::string::npos)
144 hex.replace(pos, 1,
"");
145 remove_spaces_in_place(hex);
149 static std::string remove_spaces(
const std::string& hex)
151 std::string copy(hex);
152 remove_spaces_in_place(copy);
ser4cpp header-only library namespace