简体   繁体   English

C ++将字符串转换为十六进制字符串的最有效方法

[英]C++ most efficient way of transforming string to hex string

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. 我还想知道是否有更简单的方法,但是如果有,那么,它们在性能上的取舍。

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 (eg a std::string , as in your code). 避免这种情况的一种好方法是让调用方传递一个缓冲区以将结果放入其中,并使用动态分配合适的缓冲区(例如,如您的代码中的std::string )来提供默认包装器。

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. 但是,除非测量显示该功能绝对是至关重要的性能,否则很可能只是浪费工作:这当然不是要做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM