c语言字符串转换为16进制和10进制数字
字符串转换为16进制或者10进制:1、使用自己编写的函数。2、使用库函数。
将字符串转换为16进制两种方法的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int HexStr2Int(char *buf)
{
int result = 0;
int tmp;
int len,i;
len = strlen(buf);
printf("len=%d
",len);
for(i = 0;i<len;i++)
{
if(*buf>="A"&& *buf<= "Z")
tmp = *buf-"A"+10;
else if(*buf>="a"&& *buf<= "z")
tmp = *buf-"a"+10;
else
tmp = *buf-"0";
result*=16;
result+=tmp;
buf++;
}
return result;
}
将字符串转换为十进制三种方法的代码:
#include<stdio.h>
#include<stdlib.h>
int Myatoi(char *buf)
{
int result = 0;
char ch;
while((ch = *(buf++)) != " ")
{
result = result*10 + ch-"0";
}
return result;
}
void main()
{
char *str = "12345";
int val,val2 = 0;
int val3;
val = atoi(str);
val2 = Myatoi(str);
val3 = strtol(str,NULL,10);
printf("val=%d,val2=%d,val3=%d
",val,val2,val3);
}
因为之前串口通讯中经常会用到,记录在此方便以后自己查阅。
- 上一篇: php定时自动执行任务(后台执行)
- 下一篇: Pandas Python读取CSV文件中的某一列