C++中 如何将整数转换成十六进制的字符串

给出一个实现的函数,要求参数只有int(转换的数)以及bits(十六进制的位数),如果十六进制不足,则补充为0;如 25 转换成 001 9

1、首先打开vc6.0, 新建一个项目。

2、添加头文件。

3、添加main主函数。

4、定义无符号char类型变量str,strH。

5、定义int变量i,j。

6、将str字符转换为十六进制并添加到strH中。

7、使用printf打印即可。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-23
用字符串流就可以。
#include <sstream>
#include <string>

std::string dec2hex(int i, int width)
{
std::stringstream ioss; //定义字符串流
std::string s_temp; //存放转化后字符
ioss << std::hex << i; //以十六制形式输出
ioss >> s_temp;
std::string s(width - s_temp.size(), '0'); //补0
s += s_temp; //合并
return s;
}

如按下面调用
std::cout << dec2hex(25, 4);
输出0019本回答被提问者采纳
第2个回答  2010-07-11
没说清楚是控制台输出还是返回字符串啊。
我就写输出到控制台吧。
int outputDec2hex(int dec, int bits)
{
char outputFormat[50] = "";

if(0 >= bits)
{
return (-1);
}

sprintf(outputFormat,"%%0%dx\n", bits);
printf(outputFormat,dec);

return 0;
}
第3个回答  2020-07-13
itoa,最后一个参数写16
相似回答