diff --git a/src/base/system.cpp b/src/base/system.cpp index eab8ae639..d767d1af2 100644 --- a/src/base/system.cpp +++ b/src/base/system.cpp @@ -3041,15 +3041,16 @@ int str_countchr(const char *haystack, char needle) void str_hex(char *dst, int dst_size, const void *data, int data_size) { static const char hex[] = "0123456789ABCDEF"; - int b; - - for(b = 0; b < data_size && b < dst_size / 4 - 4; b++) + int data_index; + int dst_index; + for(data_index = 0, dst_index = 0; data_index < data_size && dst_index < dst_size - 3; data_index++) { - dst[b * 3] = hex[((const unsigned char *)data)[b] >> 4]; - dst[b * 3 + 1] = hex[((const unsigned char *)data)[b] & 0xf]; - dst[b * 3 + 2] = ' '; - dst[b * 3 + 3] = 0; + dst[data_index * 3] = hex[((const unsigned char *)data)[data_index] >> 4]; + dst[data_index * 3 + 1] = hex[((const unsigned char *)data)[data_index] & 0xf]; + dst[data_index * 3 + 2] = ' '; + dst_index += 3; } + dst[dst_index] = '\0'; } static int hexval(char x) diff --git a/src/test/str.cpp b/src/test/str.cpp index de6ed7633..be18083b8 100644 --- a/src/test/str.cpp +++ b/src/test/str.cpp @@ -200,6 +200,38 @@ TEST(Str, EndswithNocase) str_length(ABCDEFG) - str_length(DEFG)); } +TEST(Str, HexEncode) +{ + char aOut[64]; + const char *pData = "ABCD"; + str_hex(aOut, sizeof(aOut), pData, 0); + EXPECT_STREQ(aOut, ""); + str_hex(aOut, sizeof(aOut), pData, 1); + EXPECT_STREQ(aOut, "41 "); + str_hex(aOut, sizeof(aOut), pData, 2); + EXPECT_STREQ(aOut, "41 42 "); + str_hex(aOut, sizeof(aOut), pData, 3); + EXPECT_STREQ(aOut, "41 42 43 "); + str_hex(aOut, sizeof(aOut), pData, 4); + EXPECT_STREQ(aOut, "41 42 43 44 "); + str_hex(aOut, 1, pData, 4); + EXPECT_STREQ(aOut, ""); + str_hex(aOut, 2, pData, 4); + EXPECT_STREQ(aOut, ""); + str_hex(aOut, 3, pData, 4); + EXPECT_STREQ(aOut, ""); + str_hex(aOut, 4, pData, 4); + EXPECT_STREQ(aOut, "41 "); + str_hex(aOut, 5, pData, 4); + EXPECT_STREQ(aOut, "41 "); + str_hex(aOut, 6, pData, 4); + EXPECT_STREQ(aOut, "41 "); + str_hex(aOut, 7, pData, 4); + EXPECT_STREQ(aOut, "41 42 "); + str_hex(aOut, 8, pData, 4); + EXPECT_STREQ(aOut, "41 42 "); +} + TEST(Str, HexDecode) { char aOut[5] = {'a', 'b', 'c', 'd', 0};