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}
.