chore: add string::fromHex
This commit is contained in:
@ -219,6 +219,33 @@ int fromHexChar(char c)
|
||||
}
|
||||
// clang-format on
|
||||
|
||||
std::vector<uint8_t> fromHex(const std::string &hexString)
|
||||
{
|
||||
std::vector<uint8_t> result;
|
||||
result.reserve(hexString.size() / 2);
|
||||
|
||||
size_t i = 0;
|
||||
while (i < hexString.size()) {
|
||||
if (hexString[i] == ':') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i + 2 > hexString.size()) {
|
||||
return {}; // uneven character count follows, it's unclear how to interpret it
|
||||
}
|
||||
|
||||
auto high = fromHexChar(hexString[i]);
|
||||
auto low = fromHexChar(hexString[i + 1]);
|
||||
if (high < 0 || low < 0) {
|
||||
return {};
|
||||
}
|
||||
result.push_back(high * 16 + low);
|
||||
i += 2;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void uppercase(std::string &subject)
|
||||
{
|
||||
std::transform(subject.begin(), subject.end(), subject.begin(), ::toupper);
|
||||
|
||||
@ -82,6 +82,13 @@ std::string toHex(const std::string &subject, int width, const char fill = '0');
|
||||
*/
|
||||
int fromHexChar(char c);
|
||||
|
||||
/**
|
||||
* @brief fromHex Turn the string into a std::vector<uint8_t>
|
||||
* @param hexString a Hexidecimal string
|
||||
* @return std::vector<uint8_t> version of the hex chars
|
||||
*/
|
||||
std::vector<uint8_t> fromHex(const std::string &hexString);
|
||||
|
||||
//! Convert to all uppercase
|
||||
/*!
|
||||
Convert each character in \c subject to uppercase
|
||||
|
||||
@ -86,6 +86,13 @@ TEST(StringTests, fromHexChar_plaintext_hexString)
|
||||
EXPECT_EQ(15, string::fromHexChar('F'));
|
||||
}
|
||||
|
||||
TEST(StringTests, fromHex_plaintext_hexString)
|
||||
{
|
||||
EXPECT_EQ(255, string::fromHex("FF")[0]);
|
||||
EXPECT_EQ(255, string::fromHex(":FF:EE")[0]);
|
||||
EXPECT_EQ(238, string::fromHex(":FF:EE")[1]);
|
||||
}
|
||||
|
||||
TEST(StringTests, uppercase_lowercaseInput_uppercaseOutput)
|
||||
{
|
||||
std::string subject = "12foo3BaR";
|
||||
|
||||
Reference in New Issue
Block a user