Browse Source

std_utils - add hex2bin() / bin2hex()

OS390/rc1
heck 9 months ago
parent
commit
15f7c3de60
2 changed files with 37 additions and 0 deletions
  1. +34
    -0
      src/std_utils.cc
  2. +3
    -0
      src/std_utils.hh

+ 34
- 0
src/std_utils.cc View File

@ -343,5 +343,39 @@ namespace pEp {
return ret.str();
}
std::string bin2hex(const std::vector<unsigned char> &bin)
{
std::string ret{};
std::stringstream ss{};
for (const auto &i : bin) {
ss << std::hex << std::setfill('0') << std::setw(2) << (int)i;
}
ret = ss.str();
return ret;
}
std::vector<unsigned char> hex2bin(const std::string &hex_str)
{
std::vector<unsigned char> ret{};
if ((hex_str.size() % 2) != 0) {
throw std::runtime_error("hex2bin: Invalid hex string: must be even length");
}
for (int i = 0; i < hex_str.size(); i += 2) {
std::ostringstream val_hex{};
val_hex << hex_str.at(i);
val_hex << hex_str.at(i + 1);
int val_int;
std::istringstream conv_ss{ val_hex.str() };
conv_ss >> std::hex >> val_int;
if (conv_ss.fail()) {
throw std::runtime_error("hex2bin: invalid hex string" + hex_str);
}
ret.push_back((unsigned char)val_int);
}
return ret;
}
} // namespace Utils
} // namespace pEp

+ 3
- 0
src/std_utils.hh View File

@ -94,6 +94,9 @@ namespace pEp {
unsigned char random_char(unsigned char min, unsigned char max);
std::string random_string(unsigned char min, unsigned char max, int len);
// conversion
std::vector<unsigned char> hex2bin(const std::string &hex_str);
std::string bin2hex(const std::vector<unsigned char>& bin);
} // namespace Utils
} // namespace pEp


Loading…
Cancel
Save