Skip to content

Commit

Permalink
Merge pull request bitcoin#1131 from laanwj/2012_04_hexstr
Browse files Browse the repository at this point in the history
Integrate @JoelKatz's optimized ToHex (#562) into current HexStr function
  • Loading branch information
sipa committed Apr 21, 2012
2 parents 9e32604 + 294df59 commit fa27abf
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
11 changes: 11 additions & 0 deletions src/test/util_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<unsigned char> 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");
Expand Down
23 changes: 14 additions & 9 deletions src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -361,15 +361,20 @@ inline int64 abs64(int64 n)
template<typename T>
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<char> 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<unsigned char>& vch, bool fSpaces=false)
Expand Down

0 comments on commit fa27abf

Please sign in to comment.