StringUtil: Add base support and hexadecimal functions

This commit is contained in:
Jean-Baptiste Boric
2020-12-10 22:42:04 +01:00
committed by Connor McLaughlin
parent fd39f09aa7
commit 9bd28f39a5
2 changed files with 57 additions and 18 deletions

View File

@ -2,6 +2,7 @@
#include <cctype>
#include <codecvt>
#include <cstdio>
#include <sstream>
#ifdef WIN32
#include "windows_headers.h"
@ -163,6 +164,33 @@ std::size_t Strlcpy(char* dst, const std::string_view& src, std::size_t size)
return len;
}
std::optional<std::vector<u8>> DecodeHex(const std::string_view& in)
{
std::vector<u8> data;
data.reserve(in.size()/2);
for (int i = 0; i < in.size()/2; i++) {
auto byte = StringUtil::FromChars<u8>(in.substr(i*2, 2), 16);
if (byte) {
data.push_back(*byte);
}
else {
return std::nullopt;
}
}
return { data };
}
std::string EncodeHex(const u8* data, int length)
{
std::stringstream ss;
for (int i = 0; i < length; i++) {
ss << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(data[i]);
}
return ss.str();
}
#ifdef WIN32
std::wstring UTF8StringToWideString(const std::string_view& str)