From 88dc2d6c6a4a71297c30339fc62ce60e53df5dc8 Mon Sep 17 00:00:00 2001 From: "Wladimir J. van der Laan" Date: Sat, 21 Apr 2012 20:15:25 +0200 Subject: Integrate @JoelKatz's optimized ToHex (#562) into current HexStr function --- src/test/util_tests.cpp | 11 +++++++++++ src/util.h | 23 ++++++++++++++--------- 2 files changed, 25 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index db31f4988a..0393edb1a7 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -88,8 +88,19 @@ BOOST_AUTO_TEST_CASE(util_HexStr) BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected + 5, true), "04 67 8a fd b0"); + + BOOST_CHECK_EQUAL( + HexStr(ParseHex_expected, ParseHex_expected, true), + ""); + + std::vector ParseHex_vec(ParseHex_expected, ParseHex_expected + 5); + + BOOST_CHECK_EQUAL( + HexStr(ParseHex_vec, true), + "04 67 8a fd b0"); } + BOOST_AUTO_TEST_CASE(util_DateTimeStrFormat) { BOOST_CHECK_EQUAL(DateTimeStrFormat("%x %H:%M:%S", 0), "01/01/70 00:00:00"); diff --git a/src/util.h b/src/util.h index d9ec68c620..fe8ca60b47 100644 --- a/src/util.h +++ b/src/util.h @@ -361,15 +361,20 @@ inline int64 abs64(int64 n) template std::string HexStr(const T itbegin, const T itend, bool fSpaces=false) { - if (itbegin == itend) - return ""; - const unsigned char* pbegin = (const unsigned char*)&itbegin[0]; - const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]); - std::string str; - str.reserve((pend-pbegin) * (fSpaces ? 3 : 2)); - for (const unsigned char* p = pbegin; p != pend; p++) - str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p); - return str; + std::vector rv; + static char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + rv.reserve((itend-itbegin)*3); + for(T it = itbegin; it < itend; ++it) + { + unsigned char val = (unsigned char)(*it); + if(fSpaces && it != itbegin) + rv.push_back(' '); + rv.push_back(hexmap[val>>4]); + rv.push_back(hexmap[val&15]); + } + + return std::string(rv.begin(), rv.end()); } inline std::string HexStr(const std::vector& vch, bool fSpaces=false) -- cgit v1.2.3