下面是我当前的char *到十六进制字符串的函数。我将其写为位操纵的练习。在AMD Athlon MP 2800+上,大约需要7毫秒才能将一个1000万字节的数组变为十六进制。我有什么想念的技巧或其他方式吗?我怎样才能使它更快?在g++中与-O3一起编译static const char _hex2asciiU_value[256][2] = { {'0','0'}, {'0','1'}, /* snip..., */ {'F','E'},{'F','F'} };std::string char_to_hex( const unsigned char* _pArray, unsigned int _len ){ std::string str; str.resize(_len*2); char* pszHex = &str[0]; const unsigned char* pEnd = _pArray + _len; clock_t stick, etick; stick = clock(); for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) { pszHex[0] = _hex2asciiU_value[*pChar][0]; pszHex[1] = _hex2asciiU_value[*pChar][1]; } etick = clock(); std::cout << "ticks to hexify " << etick - stick << std::endl; return str;} 更新添加了计时码 Brian R. Bondy:用堆分配的缓冲区替换std::string,并将ofs * 16更改为ofs Antti Sykäri:用替换内部循环 int upper = *pChar >> 4; int lower = *pChar & 0x0f; pszHex[0] = pHex[upper]; pszHex[1] = pHex[lower];结果〜8ms Robert:用完整的256个条目表替换_hex2asciiU_value,牺牲了内存空间,但结果〜7ms! HoyHoy:注意到它产生了不正确的结果 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您可以以更多的内存为代价来创建一个完整的256项十六进制代码表:static const char _hex2asciiU_value[256][2] = { {'0','0'}, {'0','1'}, /* ..., */ {'F','E'},{'F','F'} };然后直接索引到表中,无需摆弄任何东西。const char *pHexVal = pHex[*pChar];pszHex[0] = pHexVal[0];pszHex[1] = pHexVal[1]; (adsbygoogle = window.adsbygoogle || []).push({}); 09-06 23:09