atod, atoi,atoboo,atoint64源码实现

atoint 字符串转int32

int atoint(const char *nptr)
{
	int c;	   /* current char */
	int total; /* current total */
	int sign;  /* if '-', then negative, otherwise positive */

	/* skip whitespace */
	while (isspace((int)(unsigned char)*nptr))
		++nptr;

	c = (int)(unsigned char)*nptr++;
	sign = c; /* save sign indication */
	if (c == '-' || c == '+')
		c = (int)(unsigned char)*nptr++; /* skip sign */

	total = 0;

	while (isdigit(c))
	{
		total = 10 * total + (c - '0');	 /* accumulate digit */
		c = (int)(unsigned char)*nptr++; /* get next char */
	}

	if (sign == '-')
		return -total;
	else
		return total; /* return result, negated if necessary */
}

atodouble 字符串转double

double atodouble(const char *s)
{

	char **endptr = 0;
	register const char *p = s;
	register long double value = 0.L;
	int sign = 0;
	long double factor;
	unsigned int expo;

	while (isspace(*p))
		p++;

	if (*p == '-' || *p == '+')
		sign = *p++;

	while ((unsigned int)(*p - '0') < 10u)
		value = value * 10 + (*p++ - '0');

	if (*p == '.')
	{
		factor = 1.;
		p++;
		while ((unsigned int)(*p - '0') < 10u)

		{

			factor *= 0.1;

			value += (*p++ - '0') * factor;
		}
	}

	if ((*p | 32) == 'e')
	{

		expo = 0;
		factor = 10.L;

		switch (*++p)
		{

		case '-':

			factor = 0.1;

		case '+':

			p++;

			break;

		case '0':

		case '1':

		case '2':

		case '3':

		case '4':

		case '5':

		case '6':

		case '7':

		case '8':

		case '9':

			break;

		default:

			value = 0.L;
			p = s;
			goto done;
		}

		while ((unsigned int)(*p - '0') < 10u)
			expo = 10 * expo + (*p++ - '0');

		while (1)
		{
			if (expo & 1)
				value *= factor;

			if ((expo >>= 1) == 0)
				break;

			factor *= factor;
		}
	}

done:

	if (endptr != 0)
		*endptr = (char *)p;

	return (sign == '-' ? -value : value);
}

atobool 字符串转bool类型

	if (strcmp(nptr, "true") == 0)
	{
		return true;
	}
	else
	{
		return false;
	}

atoint64 字符串转int64

int64_t atoint64(const char *p)
{
	int64_t n;
	int c, neg = 0;
	unsigned char   *up = (unsigned char *)p;
 
	if (!isdigit(c = *up)) {
		while (isspace(c))
			c = *++up;
		switch (c) {
		case '-':
			neg++;
			/* FALLTHROUGH */
		case '+':
			c = *++up;
		}
		if (!isdigit(c))
			return (0);
	}
 
	for (n = '0' - c; isdigit(c = *++up); ) {
		n *= 10; /* two steps to avoid unnecessary overflow */
		n += '0' - c; /* accum neg to avoid surprises at MAX */
	}
 
	return (neg ? n : -n);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值