Pergunta

Possible Duplicate:
c++ template for conversion between decimal and arbitrary base

I would like to convert an instance of unsigned int to an instance of std::vector<unsigned int> in base X where X is any number from 2 to maximum number an unsigned int can represent.

EDIT: I used to say an unsigned int in base 10, but that got critical comments, and I think that's right, so I removed it to avoid confusion.

There are a lot of questions and answers on SO that cover something like itoa that converts up to base 16 or 32 or some small number (with this itoa implementation page being pointed out as good resource). I wasn't able to find a nice conversion for bases much larger than that.

Note: Performance is not a concern (within reason).

Foi útil?

Solução 2

The following code converts x to a vector in base base. It also pad the resulting vector with extra zeros if needed to satisfy minSize size of the resulting vector.

vector<unsigned int> intToAnyBase(unsigned int x, int base, int minSize = 1) {
    assert(base >= 2);

    // minSize allows us to pad the resulting vector
    // with extra zeros at the front if needed
    minSize = std::max(1, minSize);

    std::vector<unsigned int> v;
    while(x > 0) {
        res.push_back(x % base);
        x /= base;
    }

    // Append zeros to the "front" to satisfy 'minSize' requirement.
    // This also adds support for x
    if(v.size() < minSize) {
        v.reserve(minSize);
        while(v.size() < minSize)
            v.push_back(0);
    }

    std::reverse(v.begin(), v.end());

    return v;
}

Note that the resulting vector is reversed in the function so that that, for example, decimal 4 produces {1,0,0} as a result and not {0,0,1}.

Outras dicas

This should do it.

std::vector<unsigned int> result;
unsigned int base = ...;
unsigned int input = ...;
while(input) {
  result.push_back(input%base);
  input /= base;
}
std::vector<unsigned int> toBaseX(unsigned int number, unsigned int base)
{
    std::vector<unsigned int> res;

    if (number == 0)
    {
        res.push_back(0);
        return res;
    }

    while (number > 0)
    {
        unsigned int currentDigit = number % base;
        res.push_back(currentDigit);
        number /= base;
    }
    return res;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top