Skip to content

Commit fa27abf

Browse files
committed
Merge pull request bitcoin#1131 from laanwj/2012_04_hexstr
Integrate @JoelKatz's optimized ToHex (#562) into current HexStr function
2 parents 9e32604 + 294df59 commit fa27abf

File tree

2 files changed

+25
-9
lines changed

2 files changed

+25
-9
lines changed

src/test/util_tests.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,19 @@ BOOST_AUTO_TEST_CASE(util_HexStr)
8888
BOOST_CHECK_EQUAL(
8989
HexStr(ParseHex_expected, ParseHex_expected + 5, true),
9090
"04 67 8a fd b0");
91+
92+
BOOST_CHECK_EQUAL(
93+
HexStr(ParseHex_expected, ParseHex_expected, true),
94+
"");
95+
96+
std::vector<unsigned char> ParseHex_vec(ParseHex_expected, ParseHex_expected + 5);
97+
98+
BOOST_CHECK_EQUAL(
99+
HexStr(ParseHex_vec, true),
100+
"04 67 8a fd b0");
91101
}
92102

103+
93104
BOOST_AUTO_TEST_CASE(util_DateTimeStrFormat)
94105
{
95106
BOOST_CHECK_EQUAL(DateTimeStrFormat("%x %H:%M:%S", 0), "01/01/70 00:00:00");

src/util.h

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -361,15 +361,20 @@ inline int64 abs64(int64 n)
361361
template<typename T>
362362
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
363363
{
364-
if (itbegin == itend)
365-
return "";
366-
const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
367-
const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
368-
std::string str;
369-
str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
370-
for (const unsigned char* p = pbegin; p != pend; p++)
371-
str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
372-
return str;
364+
std::vector<char> rv;
365+
static char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
366+
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
367+
rv.reserve((itend-itbegin)*3);
368+
for(T it = itbegin; it < itend; ++it)
369+
{
370+
unsigned char val = (unsigned char)(*it);
371+
if(fSpaces && it != itbegin)
372+
rv.push_back(' ');
373+
rv.push_back(hexmap[val>>4]);
374+
rv.push_back(hexmap[val&15]);
375+
}
376+
377+
return std::string(rv.begin(), rv.end());
373378
}
374379

375380
inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)

0 commit comments

Comments
 (0)