我目前有这个函数可以将无符号整数转换为字符串(我需要一个适用于非标准类型的函数,如 __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;
}
有什么办法可以优化这段代码吗?
最佳答案
您可能想阅读 Alexei Alexandrescu 的这篇文章,他在文中以使用(固定基数)int 到字符串的转换为例讨论了低级优化:
https://www.facebook.com/notes/facebook-engineering/three-optimization-tips-for-c/10151361643253920
请记住,优化时最重要的事情始终是分析。
关于c++ - 整数到字符串优化函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22202058/