Created
September 9, 2019 10:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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