Archlinux
GCC 13.1.1 20230429
2023-07-22 19:48:23 星期六
点击查看代码
#include<stdio.h>
#include<ctype.h>
int htoi( const char *s );
int main()
{
char arr[4] = "0x3A";
int result = htoi(arr);
printf("%d\n", result);
return 0;
}
int htoi( const char *s )
{
int i, out;
i = out = 0;
//处理前缀
if( s[0] == '0' && ( s[1] == 'x' || s[1] == 'X') )
i = 2;
//处理字符串
while( s[i] != '\0' )
{
int tmp = 0;
char c_tmp = s[i];
if( isdigit(c_tmp) ){
tmp = c_tmp - '0';
}
else if( c_tmp >= 'A' && c_tmp <= 'F' ){
tmp = c_tmp - 'A' + 10;
}
else{
puts("字符非法!");
}
out = out * 16 + tmp;
++i;
}
return out;
}
运行截图:
0x3A的十进制数是58,输出正确。
小白刚学习C语言,代码质量不高,欢迎评论。
标签:tmp,数字,包含,int,htoi,char,字符串,前缀 From: https://www.cnblogs.com/yuwu/p/17574121.html