#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时直接返回30H 31H的话,这个数据不属于十六进制吧?我得到一组数据123,我要转化为30H 31H 30H 32H 30H 33H的格式发给下位机。
追答//这样满足要求么?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