#includechar str[4]="0xdc"; unsigned char str2hex(char *str) { int i; unsigned char temp[2],hex; for(i=2; str[i]!=' '; 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个字符串如:0xffn"); scanf("%s",str); unsigned char hex=str2hex(str); printf("hex=0x%xn转换完成nnnn",hex); } }
输出:
str2hex转换 请输入4个字符串如:0xff 0x44 hex=0x44 转换完成 str2hex转换 请输入4个字符串如:0xff 0x99 hex=0x99 转换完成 str2hex转换 请输入4个字符串如:0xff



