Skip to content

Commit

Permalink
utils: convert hex <-> bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
rtgiskard committed Oct 1, 2024
1 parent 7816fd0 commit ec3f2e0
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/utils/misc.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include <format>
#include <sstream>
#include <string>

#include "misc.h"

namespace mtrx {
namespace utils {

std::string hexFromBytes(const uint8_t * bytes, const uint32_t size) {
std::ostringstream oss;
for (uint32_t i = 0; i < size; i++)
oss << std::format("{:02x}", bytes[i]);
return oss.str();
}

bool hexToBytes(const std::string & hex, uint8_t * bytes, const uint32_t size) {
if (hex.size() != size * 2)
return false;

for (auto c : hex)
if (!std::isxdigit(c))
return false;

for (uint32_t i = 0; i < size; i++)
bytes[i] = std::stoul(hex.substr(i * 2, 2), nullptr, 16);

return true;
}

}; // namespace utils
}; // namespace mtrx
16 changes: 16 additions & 0 deletions src/utils/misc.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#ifndef INCLUDE_UTILS_MISC_H
#define INCLUDE_UTILS_MISC_H

#include <cstdint>
#include <string>

namespace mtrx {
namespace utils {

std::string hexFromBytes(const uint8_t * bytes, const uint32_t size);
bool hexToBytes(const std::string & hex, uint8_t * bytes, const uint32_t size);

}; // namespace utils
}; // namespace mtrx

#endif

0 comments on commit ec3f2e0

Please sign in to comment.