hyperledger/iroha
Iroha - A simple, decentralized ledger http://iroha.tech
hexutils.hpp
Go to the documentation of this file.
1 
5 #ifndef IROHA_HEXUTILS_HPP
6 #define IROHA_HEXUTILS_HPP
7 
8 #include <ciso646>
9 #include <iomanip>
10 #include <sstream>
11 #include <string>
12 
13 #include <boost/optional.hpp>
14 
15 namespace iroha {
16 
22  inline std::string bytestringToHexstring(const std::string &str) {
23  std::stringstream ss;
24  ss << std::hex << std::setfill('0');
25  for (const auto &c : str) {
26  ss << std::setw(2) << (static_cast<int>(c) & 0xff);
27  }
28  return ss.str();
29  }
30 
37  inline boost::optional<std::string> hexstringToBytestring(
38  const std::string &str) {
39  if (str.empty() or str.size() % 2 != 0) {
40  return boost::none;
41  }
42  std::string result(str.size() / 2, 0);
43  for (size_t i = 0; i < result.length(); ++i) {
44  std::string byte = str.substr(i * 2, 2);
45  size_t pos = 0; // processed characters count
46  try {
47  result.at(i) =
48  static_cast<std::string::value_type>(std::stoul(byte, &pos, 16));
49  } catch (const std::invalid_argument &) {
50  return boost::none;
51  } catch (const std::out_of_range &) {
52  return boost::none;
53  }
54  if (pos != byte.size()) {
55  return boost::none;
56  }
57  }
58  return result;
59  }
60 
61 } // namespace iroha
62 
63 #endif // IROHA_HEXUTILS_HPP
Definition: block_query.hpp:14
boost::optional< std::string > hexstringToBytestring(const std::string &str)
Definition: hexutils.hpp:37
std::string bytestringToHexstring(const std::string &str)
Definition: hexutils.hpp:22