Manually print an N-byte integer

What is a scalable algorithm for printing an integer N-binary number whose value does not match long long. I know that printfboth friends, as well <iostream>(which are most likely copied to <cstdio>, have a built-in for standard types, but I would like to do this for an integer consisting of N bytes.

I thought about it and worked a bit at googled, but it always comes down to using an already existing libitary bigint, such as GMP (a code base that I am not familiar with at all) or “using printf” or the most useful one is “difficult”.

The integer is basically:

template<size_t N>
class Integer{
...
private:
    int8_t first;
    uint8_t rest[N-1];
}

therefore reinterpreting the byte Integer<4>will lead you to int32_t. I would like to scale it to N> 8. At the moment, efficiency is not my problem. Nor is it the end (this is for x86).

+5
source share
2 answers

Step 1: Define a lookup table containing the permissions of the two in row format:

const char * const powers_of_two[] = {"1", "2", "4", "8", "16", "32", "64", ...};

Step 2: Write a function that adds two numbers to the string format.

Step 3: Iterate over the bits of your number and add all the lines corresponding to 1 bit.

Step 4. Print the result.

I myself used this approach to print very large floating point numbers, and it worked fine for me.

+5
source

Basic recursive algorithm for decimal number output:

void negate(Integer & number); // modifies the input
int divide_by_10(Integer & number); // modifies the input
bool is_zero(const Integer & number);

void output_number(Integer number)
{
    if (number.first < 0)
    {
        cout << "-";
        negate(number);
    }
    if (is_zero(number))
    {
        cout << "0";
        return;
    }
    int remainder = divide_by_10(number);
    if (!is_zero(number))
        output_number(number);
    char digit[] = {'0', 0};
    digit[0] += remainder;
    cout << digit;
}

undefined, , .

+2

All Articles