为什么这段代码没有给我正确的大数值?跟我用大于32位的数字有关系吗?如果是这样,我如何让我的函数接受任何位大小的值?我会重载功能吗?这似乎有点浪费空间
std::string makehex(unsigned int value, unsigned int size = 2){
std::string out;
while (value > 0){
out = h[value % 16] + out;
value /= 16;
}
while (out.size() < size)
out = "0" + out;
return out;
}
编辑:用法:
std::string value = makehex(30, 5);
std::cout << value; // 0001e
最佳答案
template<typename T>
std::string makehex(T value, const unsigned size = 2 * sizeof(T))
{
std::string out(size, '0');
while (value && size){
out[--size] = "0123456789abcdef"[value & 0x0f];
value >>= 4;
}
return out;
}
关于c++ - 我的 int to hex 函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6102658/