//整数转换成字符串——IntToString.h
#ifdef __cplusplus
extern "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
整数与字符串互转
最新推荐文章于 2023-04-21 10:06:32 发布