C语言将0XFF类似格式的字符串转换为HEX数据
#include <stdio.h>
char str[4]="0xdc";
unsigned char str2hex(char *str)
{
int i;
unsigned char temp[2],hex;
for(i=2; str[i]!='\0'; i++)
{
if((str[i]>='0')&&(str[i]<='9'))
{
temp[i-2]=str[i]-0x30;//字符0为0x30,‘0’-‘0’=0x0 ,'9'-'0'=0x9
}
else if((str[i]>='A')&&(str[i]<='F'))
{
temp[i-2]=str[i]-0X37;//字符'A'为0x41,'A'-(0X37)=0xa
}
else if((str[i]>='a')&&(str[i]<='f'))
{
temp[i-2]=str[i]-0X57;//字符'a'为0x61,'a'-(0X57)=0xa
}
}
return hex=(temp[0]<<4)|temp[1];
}
int main()
{
while(1)
{
printf("str2hex转换\n");
printf("请输入4个字符串如:0xff\n");
scanf("%s",str);
unsigned char hex=str2hex(str);
printf("hex=0x%x\n转换完成\n\n\n\n",hex);
}
}
输出:
str2hex转换
请输入4个字符串如:0xff
0x44
hex=0x44
转换完成
str2hex转换
请输入4个字符串如:0xff
0x99
hex=0x99
转换完成
str2hex转换
请输入4个字符串如:0xff