Utils: Add a ByteArrayToHexString helper

This commit is contained in:
Peter Keresztes Schmidt 2021-05-26 20:03:40 +02:00
parent 62f60b76d6
commit d2932b5d68
3 changed files with 33 additions and 0 deletions

View File

@ -116,6 +116,23 @@ std::string Join(const StringVector &values, const std::string &delim) {
return ss.str(); return ss.str();
} }
std::string ByteArrayToHexString(nonstd::span<const uint8> bytes) {
static constexpr char lowercase_table[] = "0123456789abcdef";
std::string buf;
buf.resize(2 * bytes.size());
const uint8 *srcPtr = bytes.data();
char *dstPtr = &buf[0];
for (size_t i = 0; i < bytes.size(); ++i) {
uint8 c = *srcPtr++;
*dstPtr++ = lowercase_table[c >> 4];
*dstPtr++ = lowercase_table[c & 0x0f];
}
return buf;
}
std::string Base64Encode(const std::string &str) { std::string Base64Encode(const std::string &str) {
static char base64_table[64] = {'\0'}; static char base64_table[64] = {'\0'};

View File

@ -20,12 +20,14 @@
#ifndef ZM_UTILS_H #ifndef ZM_UTILS_H
#define ZM_UTILS_H #define ZM_UTILS_H
#include "zm_define.h"
#include <algorithm> #include <algorithm>
#include <chrono> #include <chrono>
#include <ctime> #include <ctime>
#include <functional> #include <functional>
#include <map> #include <map>
#include <memory> #include <memory>
#include "span.hpp"
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <sys/time.h> #include <sys/time.h>
@ -67,6 +69,8 @@ std::string stringtf(const std::string &format, Args... args) {
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
} }
std::string ByteArrayToHexString(nonstd::span<const uint8> bytes);
std::string Base64Encode(const std::string &str); std::string Base64Encode(const std::string &str);
void TimespecDiff(timespec *start, timespec *end, timespec *diff); void TimespecDiff(timespec *start, timespec *end, timespec *diff);

View File

@ -140,6 +140,18 @@ TEST_CASE("Join") {
REQUIRE(Join({"a", "b"}, "") == "ab"); REQUIRE(Join({"a", "b"}, "") == "ab");
} }
TEST_CASE("ByteArrayToHexString") {
std::vector<uint8> bytes;
REQUIRE(ByteArrayToHexString(bytes) == "");
bytes = {0x00};
REQUIRE(ByteArrayToHexString(bytes) == "00");
bytes = {0x00, 0x01, 0x02, 0xff};
REQUIRE(ByteArrayToHexString(bytes) == "000102ff");
}
TEST_CASE("Base64Encode") { TEST_CASE("Base64Encode") {
REQUIRE(Base64Encode("") == ""); REQUIRE(Base64Encode("") == "");
REQUIRE(Base64Encode("f") == "Zg=="); REQUIRE(Base64Encode("f") == "Zg==");