sigalor
sigalor

Reputation: 1369

Convert big hexadecimal to decimal numbers

I have a big hexadecimal number, for example CD4A0619FB0907BC00000 (25!) or any other number like this. Now, using standard C/C++ code only (no libraries like Boost), I want to convert this number to the decimal number 15511210043330985984000000. Unfortunately, it's too big for a 64 bit integer (like long long) and I don't want to use any floating point data types either. If this is possible at all, how can you do this?

Upvotes: 0

Views: 1992

Answers (3)

rcnjko
rcnjko

Reputation: 51

vector<unsigned int> bin2dec(vector<unsigned int> binary)
{
    vector<unsigned int> decimal;
    bool all_zero = false;

    // binary[i]: stores 8-bit of the nubmer.
    // Ex. 258 = 0x102 => binary[0] = 0x2, binary[1] = 0x1.
    while (!all_zero) {
        all_zero = true;
        for (int i = binary.size() - 1; i >= 0; i--) {
            int q = binary[i] / 10;
            int r = binary[i] % 10;

            binary[i] = q;
            if (i > 0) {
                binary[i-1] += (r << 8);
            } else {
                decimal.insert(decimal.begin(), r);
            }
            if (q != 0) {
                all_zero = false;
            }
        }
    }
    // each element stands for one digit of the decimal number.
    // Ex. 258 => decimal[0] = 2, decimal[1] = 5, decimal[2] = 8.
    return decimal; 
}

Upvotes: 1

Daniel
Daniel

Reputation: 8431

If you don't want to use external libraries then you will have to implement a arbitary-precision integer type yourself. See this question for ideas on how to do this. You will also need a function/constructor for converting hexadecimal strings to your new type. See this question for ideas on how to do this.

Upvotes: 0

JSF
JSF

Reputation: 5311

Assuming you don't want to use any of resources that might fit your description "libraries like Boost". The simple answer is to write your own subset of one, with just the operations you need. If 32 hex digits is enough, then simplest would be to create your own 128 bit unsigned int and code a divide by 10 function (producing quotient and remainder) for that 128-bit int. You really don't need any other functions and divide by 10 is pretty easy. Converting up to 32 hex digits to 128 bit int is trivial and generating decimal output from a series of divide by ten is trivial. If you want essentially unlimited size, then it is likely simpler to represent a decimal number as a string of digits and write a routine to multiply that by 16 and add in another digit. That would never be the efficient solution, just likely easier to code for your purpose and unlimited size.

Upvotes: 1

Related Questions