Utils: Add a ByteArrayToHexString helper
This commit is contained in:
parent
62f60b76d6
commit
d2932b5d68
|
@ -116,6 +116,23 @@ std::string Join(const StringVector &values, const std::string &delim) {
|
|||
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) {
|
||||
static char base64_table[64] = {'\0'};
|
||||
|
||||
|
|
|
@ -20,12 +20,14 @@
|
|||
#ifndef ZM_UTILS_H
|
||||
#define ZM_UTILS_H
|
||||
|
||||
#include "zm_define.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include "span.hpp"
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#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
|
||||
}
|
||||
|
||||
std::string ByteArrayToHexString(nonstd::span<const uint8> bytes);
|
||||
|
||||
std::string Base64Encode(const std::string &str);
|
||||
|
||||
void TimespecDiff(timespec *start, timespec *end, timespec *diff);
|
||||
|
|
|
@ -140,6 +140,18 @@ TEST_CASE("Join") {
|
|||
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") {
|
||||
REQUIRE(Base64Encode("") == "");
|
||||
REQUIRE(Base64Encode("f") == "Zg==");
|
||||
|
|
Loading…
Reference in New Issue