C++中如何将整数转换为十六进制数,如整数1,转换为十六进制是0x01,我需要返回的是30 31。谢谢

2025-04-14 09:34:29
推荐回答(2个)
回答1:

以下代码实测OK,请采纳,亲 

#include

#include

using namespace std;

unsigned short str2hex(char m)

{

0x3000|(unsigned short)(m);

if((m>='0')&&(m<='9'))

return 0x3000|(unsigned short)(m);

else //其他字符直接忽略 

return 0;

}

int main()

{

char s[]="123";

char *p = s;

unsigned short t;

cout << endl;

while(*p)

{

t = str2hex(*p);

if(p!=s) cout << ",";

cout << "0x" << char( (t&0xff00) >> 8) << char (t&0x00ff);

p++;

}

cout << endl;

return 0;

}

回答2:

还是没有明白:感觉这和16进制没有啥关系呢?如果输入只包含0-9字符,并且把每个字符单独的看的话。
是不是只包含下面的转换关系:
1 - 30 31
2 - 30 32
3 - 30 33
……
9 - 30 39?