字符转整型,比系统的好用!a2iLxx (涵盖 16进制,VC6亲测可用)请提出宝贵意见~

#include "string.h"
#define INVALID_VALUE_LXX	((1 << (8 * sizeof(int) -1)) - 1)	
/*有符号整型最大值,如果越界将为0, and - is prioty of <<*/
#define A2a(ch) (('a' <= (ch) && (ch) <= 'f') ? (ch) : ((ch) - 'A' + 'a'))

bool is0to9(char ch)
{
	if ('0' <= ch && ch <= '9')
	{
		return true;
	}
	else
	{
		return false;
	}
}

bool isatoF(char ch)
{
	if (('a' <= ch && ch <= 'f') || ('A' < ch && ch <= 'F'))
	{
		return true;
	}
	else
	{
		return false;
	}
}

int a2iLxx(char* ch)
{
	int index = 0;
	int retVal = 0;
	bool flag = false;
	if (NULL == ch)
	{
		return INVALID_VALUE_LXX;
	}

	/*Ox*/
	if ('0' == ch[0] && ('x' == ch[1] || 'X' == ch[1]))
	{
		index = 2;
		for (; ch[index] != '\0'; index++)
		{
			/* x * 2^y == x * 1 << y */
			if (is0to9(ch[index]))
			{
				retVal = (retVal << 4) + ch[index] - '0';
				continue;
			}
			
			if (isatoF(ch[index]))
			{
				retVal = (retVal << 4) + 10 + A2a(ch[index]) - 'a';
				continue;
			}

			return INVALID_VALUE_LXX;

		}
		return retVal;
	}

	/*10*/
	index = 0;
	if ('-' == ch[0])
	{
		/*负数*/
		flag = true;
		index = 1;
	}

	for (; ch[index] != '\0'; index++)
	{
		if (!is0to9(ch[index]))
		{
			return INVALID_VALUE_LXX;
		}
		retVal = retVal * 10 + ch[index] - '0';
	}

	if (flag)
	{
		return -retVal;
	}
	else
	{
		return retVal;
	}
}

void main()
{
	char ch1[] = "123";
	char ch2[] = "-234";
	char ch3[] = "0";
	char ch4[] = "0x123";
	char ch5[] = "0xff";
	int a = INVALID_VALUE_LXX;
	char d1 = A2a('a');
	char d2 = A2a('B');
	/*调试查看值*/
	a = a2iLxx(ch1);
	a = a2iLxx(ch2);
	a = a2iLxx(ch3);
	a = a2iLxx(ch4);
	a = a2iLxx(ch5);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值