【发布时间】:2014-04-07 18:21:44
【问题描述】:
我目前有这个函数可以将无符号整数转换为字符串(我需要一个适用于__uint128_t 等非标准类型的函数):
#include <iostream>
#include <algorithm>
#include <string>
template <typename UnsignedIntegral>
std::string stringify(UnsignedIntegral number, const unsigned int base)
{
static const char zero = '0';
static const char alpha = 'A';
static const char ten = 10;
std::string result;
char remainder = 0;
do {
remainder = number%base;
result += (remainder < ten) ? (zero+remainder) : (alpha+remainder-ten);
number /= base;
} while (number > 0);
std::reverse(std::begin(result), std::end(result));
return result;
}
int main()
{
std::cout<<stringify(126349823, 2)<<std::endl;
return 0;
}
有没有办法优化这段代码?
【问题讨论】:
-
一种方法是将一组可能的“数字”存储为一个静态数组(0 到 9 后跟 A 到 Z)并对其进行索引,而不是使用条件来决定是否使用数字或字母。此外,对于常用的碱基,如 2、8、10 和 16,您可以为这些碱基提供具有优化算法的模板特化。
-
这看起来更适合codereview,因为它是关于改进有效的代码,而不是修复无效的代码。
-
嗯...
sprintf?您真的希望通过优化获得超过 0.5% 的收益吗? -
@Angew 你不是说不满足性能要求算作不工作吗?
-
在@dvnrrs 之后,当基数是 2 的幂时,使用按位运算而不是非常昂贵的 % 和 /。你也可以通过使用恒等式 A % B = A - (A / B) * B 来避免使用 %(你用 % 换*)。而当已知底数不超过 10 时,就没有十六进制数字了。
标签: c++ string optimization c++11 integer