diff options
-rw-r--r-- | base/string_util.cc | 29 | ||||
-rw-r--r-- | base/string_util.h | 10 | ||||
-rw-r--r-- | base/string_util_unittest.cc | 8 |
3 files changed, 46 insertions, 1 deletions
diff --git a/base/string_util.cc b/base/string_util.cc index eae60d2..45a4442 100644 --- a/base/string_util.cc +++ b/base/string_util.cc @@ -1532,3 +1532,32 @@ bool ElideString(const std::wstring& input, int max_len, std::wstring* output) { return true; } + +std::string HexEncode(const void* bytes, size_t size) { + static const char kHexChars[] = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + + if (size == 0) + return std::string(); + + std::string ret; + // For each byte, we print two characters. + ret.resize(size * 2); + + const unsigned char* pos = reinterpret_cast<const unsigned char*>(bytes); + const unsigned char* end = pos + size; + std::string::iterator write = ret.begin(); + while (pos < end) { + unsigned char b = *pos; + pos++; + + write[0] = kHexChars[(b >> 4) & 0xf]; + write++; + + write[0] = kHexChars[b & 0xf]; + write++; + } + + return ret; +} diff --git a/base/string_util.h b/base/string_util.h index 6d7ff94..68142cb 100644 --- a/base/string_util.h +++ b/base/string_util.h @@ -539,5 +539,13 @@ bool ElideString(const std::wstring& input, int max_len, std::wstring* output); bool MatchPattern(const std::wstring& string, const std::wstring& pattern); bool MatchPattern(const std::string& string, const std::string& pattern); -#endif // BASE_STRING_UTIL_H_ +// Returns a hex string representation of a binary buffer. +// The returned hex string will be in upper case. +// This function does not check if |size| is within reasonable limits since +// it's written with trusted data in mind. +// If you suspect that the data you want to format might be large, +// the absolute max size for |size| should be is +// std::numeric_limits<size_t>::max() / 2 +std::string HexEncode(const void* bytes, size_t size); +#endif // BASE_STRING_UTIL_H_ diff --git a/base/string_util_unittest.cc b/base/string_util_unittest.cc index 11c727d..0ca4438 100644 --- a/base/string_util_unittest.cc +++ b/base/string_util_unittest.cc @@ -1451,3 +1451,11 @@ TEST(StringUtilTest, ElideString) { EXPECT_TRUE(output == cases[i].output); } } + +TEST(StringUtilTest, HexEncode) { + std::string hex(HexEncode(NULL, 0)); + EXPECT_EQ(hex.length(), 0U); + unsigned char bytes[] = {0x01, 0xff, 0x02, 0xfe, 0x03}; + hex = HexEncode(bytes, sizeof(bytes)); + EXPECT_EQ(hex.compare("01FF02FE03"), 0); +} |