2021.11.21 进阶的atoi函数(进制转换)和strtol函数

69 篇文章 3 订阅

1. 十六进制、十进制、八进制

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<assert.h>
static int to_Hex(const char *str)//十六进制函数
{
	//十六进制只有  0123456789abcdef/ABCDEF
	int sum = 0;
	while (isxdigit(*str))//isxdigit()判断是否为十六进制数
	{
		if (isdigit(*str)) //判断是否为数字
		{
			sum = sum * 16 + *str - '0';
		}
		else
		{
			tolower(*str);   //将大写字母转化为小写字母
			sum = sum * 16 + *str - 'a' + 10;
		}
		str++;
	}
	return sum;
}
static int to_Dec(const char* str) //十进制函数
{
	//十进制的话只有数字:0123456789
	int sum = 0;
	while (isdigit(*str))
	{
		sum = sum * 10 + *str - '0';
		str++;
	}
	return sum;
}
static int to_Oct(const char* str)//八进制函数
{
	//八进制数字有:01234567
	int sum = 0;
	while (isdigit(*str) && *str != '8' && *str != '9')
	{
		sum = sum * 8 + *str - '0';
		str++;
	}
	return sum;
}
//前加static表示是静态函数,只能在本文件调用,不能在同工程中,其它C文件调用使用static,可以避免不想被其它模块调用的函数调用
int My_atoi(const char *str)
{
	assert(*str != NULL);
	if (*str == NULL)
	{
		return NULL;
	}
	int index = 1;//正负标记
	int sum = 0;
	while (isspace(*str))
	{
		str++;
	}
	if (*str == '-')
	{
		index = -index;
		str++;
	}
	if (*str == '+')
	{
		str++;
	}
	if (*str == '0')
	{
		if (*(str + 1) == 'x' || *(str + 1) == 'X')
		{
			sum = to_Hex(str + 2);//十六进制→存储方式‘0x18’
		}
		else
		{
			sum = to_Oct(str + 1);//八进制→存储方式‘018’
		}
	}
	else
	{
		sum = to_Dec(str);
	}
	return sum*index;
}
int main()
{
	const char* str = "0X100";
    //const char* str = "0100";
    //const char* str = "100";
	int tmp = My_atoi(str);
	printf("%d\n", tmp);
	return 0;
}

运行结果:

"0X100"

 "0100"

 "100"

 2. strtol函数:将字符串转换为长整型(任何进制)


                第一个参数:字符串开始地址  
                第二个参数:二级指针,返回字符串解析时停下来的位置  
                第三个参数:X进制

应用代码:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    const char* str2 = "100abc!";
    char* p;
    int flg = strtol(str2, &p, 16);
    printf("%d\n", flg);
    printf("%s\n", p);
    return 0;
}

运行结果:

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值