方法一
转载于: https://my.oschina.net/u/3273849/blog/3102150
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
std::string dec2hex(int i, int width)
{
std::stringstream ioss; //定义字符串流
std::string s_temp; //存放转化后字符
ioss << std::hex << i; //以十六制形式输出
ioss >> s_temp;
if(width > s_temp.size())
{
std::string s_0(width - s_temp.size(), '0'); //位数不够则补0
s_temp = s_0 + s_temp; //合并
}
std::string s = "0x" + s_temp.substr(s_temp.length() - width, s_temp.length()); //取右width位
return s;
}
int main()
{
int i = 259;
std::string str = dec2hex(i,4);
cout << str <<endl;
return 0;
}
输出:
0x0103
方法2:
int main()
{
int i = 259;
char str[6];
sprintf(str, "0x0%x", i);
cout << str <<endl;
return 0;
}
输出:
0x0103