0

I have this:

std::string TCPMessengerServer::hexStr(unsigned char *data, int len)
{

    constexpr char hexmap[] = { '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    std::string s(len * 2, ' ');
    for (int i = 0; i < len; ++i) {
        s[2 * i] = hexmap[(data[i] & 0xF0) >> 4];
        s[2 * i + 1] = hexmap[data[i] & 0x0F];
    }
    return s;
}

However, I would like to know if there is a more efficient way of doing this. I'd also like to know if there are easier ways, but if so, what performance trade-offs they present.

10
  • Avoiding the possible dynamic memory allocation will be more efficient for strings over a few chars long. Commented Jan 24, 2016 at 20:16
  • Why not use a std::ostringstream and the std::hex stream manipulator? Commented Jan 24, 2016 at 20:18
  • 1
    @JoachimPileborg: that would be less efficient, not more. Commented Jan 24, 2016 at 20:18
  • 1
    @101010: they're bytes,. Commented Jan 24, 2016 at 20:19
  • 1
    @Cheersandhth.-Alf Maybe true, but unless this function is called hundred of times each second I'd say go for simplicity. Commented Jan 24, 2016 at 20:23

1 Answer 1

0

Avoiding the possible dynamic memory allocation will be more efficient for strings over a few chars long.

A good way to avoid when possible, is to let the caller pass a buffer to place the result in, and to provide a default wrapper using dynamic allocation of a suitable buffer (e.g. a std::string, as in your code).

However, unless measurements show this function to be absolutely critical performance-wise, that's most probably just wasted work: it's not something to do as a matter of course.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.