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

#include<iostream>
using namespace std;
int str2hex(char m)
{
if((m>='0')&&(m<='9'))
return m-0x30;
else //其他字符直接忽略
return 0;
}
int main()
{
char a='B';
cout<<str2hex(a)<<endl;
}
假如是输入一个数组,里面只含有0~9的字符,我需要得到每一个字符对应的十六进制。如数组是[123],则输出为0x01,0x02,0x03,返回值为30 31 30 32 30 33,并不是把123当一个整体字符串。

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

#include <iostream>

#include <string>

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;

}

追问

可以解释下while循环里面的吗,谢谢啦

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-12-09
还是没有明白:感觉这和16进制没有啥关系呢?如果输入只包含0-9字符,并且把每个字符单独的看的话。
是不是只包含下面的转换关系:
1 - 30 31
2 - 30 32
3 - 30 33
……
9 - 30 39?追问

对的,只包含这种关系。但是假如我仅仅是当判断为1时直接返回30H 31H的话,这个数据不属于十六进制吧?我得到一组数据123,我要转化为30H 31H 30H 32H 30H 33H的格式发给下位机。

追答//这样满足要求么?
#include<iostream>
#include<string>
using namespace std;

int main(){
string tar;
cin>>tar;
int count = 0;
while(tar[count]!='\0'){
cout<<"30H ";
cout<<"3"<<tar[count]<<"H ";
count++;
}
cout<<endl;
return 0;
}

input: 131243242342

output: 30H 31H 30H 33H 30H 31H 30H 32H 30H 34H 30H 33H 30H 32H 30H 34H 30H 32H 30H 33H

30H 34H 30H 32H

相似回答