整数与字符串互转
来源:互联网 发布:八百字淘宝导购 编辑:程序博客网 时间:2024/05/22 09:35
//整数转换成字符串——IntToString.h#ifdef __cplusplusextern "C"{#endif#ifndef __INT_TO_STRING__#define __INT_TO_STRING__char* IntToString(int num,char* str,int radix){ //索引表 char index[] = "0123456789ABCDEF"; unsigned ui_num;//将int——》unsigned的中间值 int i_index = 0;//char中的地址偏移量 if( radix == 10 && num < 0 )//十进制负数转为正数 { ui_num = (unsigned)-num; str[i_index++] = '-'; } else { ui_num = (unsigned)num; } do{ str[i_index++] = index[ui_num % radix]; ui_num /= radix; }while(ui_num != 0); str[i_index] = '\0'; i_index--; int j = 0 ,sign = 0; if ( str[0] == '-') { j = 1; sign = 1; } for( ; j <= i_index /2 ; j++) { char temp = str[j]; str[j] = str[i_index-j+sign]; str[i_index-j+sign] = temp; } return str;}enum int_flag{uncorrect,correct};int g_flag = uncorrect;int StringToInt(const char* str){ int postive = 1; int i_firstIn = 0; unsigned int result = 0; if( str == NULL ) { return 0; } while(*str < '1' || *str > '9')//如果不是1—9之间的数,则进行判断 { if (*str == ' ' || *str == '0')//如果是空格或是0,则继续找 { str++; continue; } else if (*str == '+' || *str == '-') { i_firstIn++; if(i_firstIn > 1)//如果+号和-号多于1个则退出 { break; } if(*str == '-') { postive = -1;} str++; } else { break;//退出 } } if(i_firstIn > 1)//如果+号和-号多于1个则退出 { return 0; } //输入的字符串符合转换要求 while (*str != '\0') { g_flag = correct; if (*str >= '0' && *str <= '9')//字符在0-9之间则转换 { result = 10 * result + (*str - '0'); str++; if ( (postive == -1 && result > (1<<(sizeof(int)*8-1)) ) || (postive == 1 && result > ~(1<<(sizeof(int)*8-1))) )//数据超出int类型的范围 { g_flag = uncorrect; result = 0; break; } } else//字符不在0-9之间则退出 { break; } } return (postive == 1) ? result :(int)(0 - result);}#endif#ifdef __cplusplus}#endif
阅读全文
0 0
- 整数与字符串互转
- C/C++整数与字符串互转
- 文章标题 整数与字符串互转
- 整数与字符串转换
- 整数与字符串转化
- 字符串,整数的互转
- 字符串和整数互转
- 关于字符串、整数互转
- php字符串转与整数比较,会把字符串转化为整数来比较
- 字符串与整数互相转换
- Java整数与字符串转换
- 字符串处理------字符串转整数
- 数字字符串转整数
- 整数转字符串
- 字符串转整数
- 字符串转整数
- 字符串转整数
- 字符串转整数
- 自己-1
- 数据库日期函数
- 数据结构--用C语言描述 耿国华 期末试题
- WebSocket 和 Socket 的区别
- 数据结构排序算法
- 整数与字符串互转
- Python设计模式-桥接模式
- 20170623
- C语言实现简易网络进程及线程间通信
- 数袋鼠好有趣
- 根据bootmode设置usb的config(for Android)
- Appium之Appium1.6.x 安装配置及问题资料汇总
- MDM USB How-to
- android增删改查以及通知栏和定时任务简单的实现