From: Pieter Lexis Date: Tue, 6 Apr 2021 21:44:51 +0000 (+0200) Subject: Add function to make a bytestring from hex X-Git-Tag: dnsdist-1.7.0-alpha1~3^2~14 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=a02d0fa6328b2fa06e99dba7db3ad65174b93c2f;p=thirdparty%2Fpdns.git Add function to make a bytestring from hex --- diff --git a/pdns/misc.cc b/pdns/misc.cc index ad3a2f4506..494e49849f 100644 --- a/pdns/misc.cc +++ b/pdns/misc.cc @@ -577,6 +577,21 @@ string makeHexDump(const string& str) return ret; } +string makeBytesFromHex(const string &in) { + if (in.size() % 2 != 0) { + throw std::range_error("odd number of bytes in hex string"); + } + string ret; + unsigned int num; + for (size_t i = 0; i < in.size(); i+=2) { + string numStr = in.substr(i, 2); + num = 0; + sscanf(numStr.c_str(), "%02x", &num); + ret.push_back((uint8_t)num); + } + return ret; +} + void normalizeTV(struct timeval& tv) { if(tv.tv_usec > 1000000) { diff --git a/pdns/misc.hh b/pdns/misc.hh index 6307293f55..d2a1ac2767 100644 --- a/pdns/misc.hh +++ b/pdns/misc.hh @@ -304,6 +304,8 @@ inline void unixDie(const string &why) } string makeHexDump(const string& str); +//! Convert the hexstring in to a byte string +string makeBytesFromHex(const string &in); void normalizeTV(struct timeval& tv); const struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs); diff --git a/pdns/test-misc_hh.cc b/pdns/test-misc_hh.cc index bc10168df2..0f591bcfd7 100644 --- a/pdns/test-misc_hh.cc +++ b/pdns/test-misc_hh.cc @@ -391,4 +391,11 @@ BOOST_AUTO_TEST_CASE(test_parseSVCBValueList) BOOST_CHECK_EQUAL(out[0], "foobar123 blabla bla,baz quux456"); } +BOOST_AUTO_TEST_CASE(test_makeBytesFromHex) { + string out = makeBytesFromHex("1234567890abcdef"); + BOOST_CHECK_EQUAL(out, "\x12\x34\x56\x78\x90\xab\xcd\xef"); + + BOOST_CHECK_THROW(makeBytesFromHex("123"), std::range_error); +} + BOOST_AUTO_TEST_SUITE_END()