以下代码转换x
为 base 中的向量base
。如果需要满足minSize
结果向量的大小,它还会用额外的零填充结果向量。
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;
}
请注意,结果向量在函数中被反转,例如,十进制 4{1,0,0}
作为结果而不是{0,0,1}
.