zoukankan      html  css  js  c++  java
  • 字符串转换成整数

    参考自:http://taop.marchtea.com/01.03.html

    下面是我实现的代码,如有不妥之处,望指正,谢谢!

    顺便提一下:

    const int INT_MAX = (int)((unsigned)~0 >> 1);
    const int INT_MIN = -(int)((unsigned)~0 >> 1) - 1;
    对0取反(得到0FFFF),然后强制转换为无符号型整数(这样移位才有意义,否则跟没有移位的结果一样,可以查看反汇编验证),再左移1位(这里对无符号整型操作,使得符号位为0,所以就得到7FFF,即有符号的最大值);
    其实当你通过反汇编验证时,就应该发现计算机中存储的是一个数的补码(毕竟计算机中的运算时通过补码实现的),而补码只有一种0,最小负数为8000(这里都是通过两个字节来讲的)。
    #include <stdio.h>
    
    const int INT_MAX = (int)((unsigned)~0 >> 1);
    const int INT_MIN = -(int)((unsigned)~0 >> 1) - 1;
    
    int StrToInt(const char *str)
    {
    	if (str == NULL)
    	{
    		printf("The string is null!");
    		exit(1);
    	}
    	int num = 0;
    	if (str[0] != '-' && str[0] == '+' || (str[0] -'0' <=9 && str[0] - '0' >=0))
    	{
    		for (int i = 0; str[i] != ''; ++i)
    		{
    			if (str[i] - '0' <= 9 && str[i] - '0' >= 0)
    			{
    				if (num > INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10))
    				{
    					num = INT_MAX;
    					break;
    				}
    				else{
    					num *= 10;
    					num += (str[i] - '0');
    				}
    			}
    			else{
    				printf("Having a wrong with input!");
    				exit(1);
    			}
    		}
    	}
    	else if (str[0] == '-'){
    		for (int i = 1; str[i] != ''; ++i)
    		{
    			if (str[i] - '0' <= 9 && str[i] - '0' >= 0)
    			{
    				if (num < INT_MIN / 10 || (num == INT_MIN / 10 && (str[i] - '0') > -(INT_MIN % 10)))
    				{
    					num = INT_MIN;
    					break;
    				}
    				else{
    					num *= 10;
    					num -= (str[i] - '0');
    				}
    			}
    			else{
    				printf("Having a wrong with input!");
    				exit(1);
    			}
    		}
    	}
    	else{
    		printf("It's wrong!");
    		exit(1);
    	}
    	return num;
    }
    
  • 相关阅读:
    .net中连接远程目录的解决方案
    VS2008+Window Mobile开发环境的搭建(转)
    安装任何版本ActiveSync都出错原因
    问题让人开始慢慢的思考
    [原创]EasyUI的TreeGrid查询功能实现
    听客户说然后再做开发
    EasyUI的DataGrid合击汇总页脚使用教程
    ASP.NET MVC 使用AderTemplate模板引擎进行视图显示
    C#的JSON数据格式转换方法
    Delphi使用ReportMachine制作小计和总计报表
  • 原文地址:https://www.cnblogs.com/mingbujian/p/5098344.html
Copyright © 2011-2022 走看看