c++ - 我的 int to hex 函数有什么问题?

标签 c++ integer hex

为什么这段代码没有给我正确的大数值?跟我用大于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;
}

演示:http://ideone.com/v04Vo

关于c++ - 我的 int to hex 函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6102658/

相关文章:

c++ - 为什么编译器不能推导模板模板参数?

c++ - 我能保证 C++ 编译器不会重新排序我的计算吗?

c++ - 为什么我的代码在阶乘返回垃圾值中查找尾随零的数量

C# 正则表达式不匹配字符串

javascript - JavaScript 中的警报格式为十六进制

c++ - 我如何检查 C++ 代码以查找所有未使用的返回值?

postgresql - 在 Postgresql 中加入整数列比加入 varchar 更有效?

java - 推土机 : Number to Number mapping is not supported

Java Integer.MIN_VALUE 的负数然后比较产生两个负数

python - python中的十六进制字符串类型转换