I have currently this function to convert an unsigned integer to a string (I need a function that works on non-standard types like __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;
}
Is there any way to optimize this code ?
You may want to read this article by Alexei Alexandrescu, where he talks about low-level optimizations by using a (fixed-radix) int to string conversion as an example:
https://www.facebook.com/notes/facebook-engineering/three-optimization-tips-for-c/10151361643253920
Keep in mind that the most important thing when optimizing is always profiling.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments