Skip to content

Instantly share code, notes, and snippets.

@jbelloncastro
Created September 9, 2019 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbelloncastro/2e939438a3ac95622ae1935e4c53333d to your computer and use it in GitHub Desktop.
Save jbelloncastro/2e939438a3ac95622ae1935e4c53333d to your computer and use it in GitHub Desktop.
Create a string from an integer without using std::to_string or std::printf
#include <algorithm>
#include <cstring>
#include <string>
#include <limits>
// Literal for the IEC Mebi binary prefix
static
std::string operator""_Mi( unsigned long long value ) {
struct Generator {
Generator( unsigned long long value ) :
remainder(value),
length(0)
{
}
char operator()() {
if( remainder == 0 )
return '\0';
char result = '0' + remainder % 10;
remainder = remainder / 10;
length++;
return result;
}
unsigned long long remainder;
unsigned char length;
};
char result[std::numeric_limits<unsigned long long>::digits10+2];
auto first = std::begin(result);
auto last = std::end(result);
Generator gen{value * 1024 * 1024};
std::generate(first, last, gen);
last = std::next(first, gen.length);
std::reverse(first, last);
return result;
}
// Type your code here, or load an example.
std::string square() {
return 64_Mi;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment