0

I was attempting to write 128 bit integer class in C++ with the number being stored in binary format across two int64_t. As I was trying to write the function that converts my number into an std::string (so I can show it somewhere like in cout) I got stuck and it raised a broader question to which I couldn't find any answer.

Consider the number 16, in memory that number is laid down that way: 00010000, unless I'm wrong, any occurrence of 16 in decimal form (in the code, as output values, debugger values, etc.) is in fact a string that contains two characters of values 49 (ASCII code for '1') and 54 (ASCII code for '6')

So how does the conversion from 00010000 (value in memory) to "16" (string) happens ?

I understand that this question sounds a bit trivial, but in my case I can't fit the numbers I want in any existing container, it would be a bit like having a 32 bit integer in binary format but no int type, how would you print the number inside it ?

Matt
  • 13
  • 4
  • This other question collected a lot of example implementations: https://stackoverflow.com/questions/4351371/c-performance-challenge-integer-to-stdstring-conversion – Ben Voigt Jun 18 '20 at 16:32
  • Does this answer your question? [How to convert an integer to an array of its digits in C++](https://stackoverflow.com/questions/60336605/how-to-convert-an-integer-to-an-array-of-its-digits-in-c) – JaMiT Jun 18 '20 at 16:38
  • 1
    Another related question: [Finding a Specific Digit of a Number](https://stackoverflow.com/questions/4410629/finding-a-specific-digit-of-a-number) – JaMiT Jun 18 '20 at 16:39

1 Answers1

0

The following code works for conversion of non-negative numbers:

#include <string>
#include <stdexcept>

std::string uint_to_string(unsigned int value, int base = 10)
{
    if(base > 36 || base < 2)
        throw std::invalid_argument("Base must be between 2 and 36");
    if(value == 0)
        return "0";
    std::string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string result;
    while(value > 0)
    {
        int digit = value % base;
        char c = digits[digit];
        result = c + result;
    }
    return result;
}
Lime
  • 28
  • 5