写了一个把数字字符串转换成整型的函数,在用二进制补码表示,其中字符串长度最大为6,允许有符号。
1、输入字符,存储符合条件的字符。
2、将存储的字符转换为整数,并用补码二进制表示。
3、输出结果。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BUFFER_SIZE 6
#define ORSTR_SIZE 20
static unsigned char buffer[BUFFER_SIZE];
static unsigned int pos=0;
/*
入口参数:待验证的数组的首地址,数组长度。
返回值 :1或0。
功能 :检验数字字符串是否合法。
*/
static int IsValid(char *temp,int orstrlen)
{
long numlong;
if(orstrlen==0)
{
printf("the string is null\n");
return 0;
}
else
{
if(!ValidStringTOBuffer(temp,orstrlen))
{
return 0;
}
else
{
if (strlen(buffer)==0)
{
printf("please input eagal string\n");
return 0;
}
else
{
numlong=atol(buffer);
if(numlong>=-32768&&numlong<=32767)
{
return 1;
}
else
{
printf("over the boundary\n");
return 0;
}
}
}
}
}
/*
入口参数:待验证的数组的首地址,数组长度。
返回值 :字符串合法时,返回合法字符;字符串不合法时,返回0。
功能 :将合法字符串存储在暂时的缓冲区buffer中。
*/
static int ValidStringTOBuffer(const char *temp,int orstrlen)
{
int i;
/* printf("call isvalidstring \n");*/
if(orstrlen>ORSTR_SIZE)
{
printf("input too long\n");
return 0;
}
else if(orstrlen==0)
{
printf("please input string\n");
return 0;
}
else
{
for(i=0;i<orstrlen;i++)
{
if(!IsValidChar(temp[i]))
{
printf("input illeagal\n");
return 0;
}
else if(temp[i]!=' ')
{
buffer[pos++]=temp[i];}
}
buffer[pos]='\0';
/*printf("the string is valid\n");*/
return 1;
}
}
/*
入口参数:待验证字符。
返回值 :1或0;
功能 :检查字符是否合法。
*/
static int IsValidChar(char ch)
{
/*printf("call isvalidchar the char is %c\n",ch);*/
if(isdigit(ch))
{
/*printf("%c is digit\n",ch);*/
return 1;
}
else if((ch=='-'||ch=='+')&&!HasDigit()&&!HasFlag())
{
/*printf("%c is flag\n",ch);*/
return 1;
}
else if((ch==' ')&&(!HasDigit())&&(!HasFlag()))
{
/*printf("%c is space\n",ch);*/
return 1;
}
else return 0;
}
/*
入口参数:无。
返回值 :1或0.
功能 :检查已存储的字符是否有数字.
*/
static int HasDigit(void)
{
int i;
for(i=0;i<pos;i++)
{if(isdigit(buffer[i]))
break;
}
return (i<pos);
}
/*
入口参数:无。
返回值 :1或0.
功能 :检验已存储的字符中是否符号。
*/
static int HasFlag(void)
{
int i;
for(i=0;i<pos&&(buffer[i]!='+'||buffer[i]!='-');i++)
;
return ((i-1)<pos);
}
/*
入口参数:待验证字符。
返回值 :1或0.
功能 :检查字符是否为数字。
*/
static int isdigit(char ch)
{
if(ch>='0'&&ch<='9')
{/*printf("%c is a digit\n",ch);*/
return 1;}
else
{/*printf("%c isn't a digit\n",ch);*/
return 0;
}
}
/*
入口参数:待转换的整型数。
返回值 :整型数转换后的二进制补码。
功能 :将整型数转换为二进制补码。
*/
void IntToBin(int numint)
{
int i;
unsigned int nummask=1;
int result[16]={0};
for(i=0;i<16;i++)
{
result[i]=(nummask&numint)>>i;
nummask=nummask<<1;
}
printf("string to bin is:");
for (i=15; i>=0; i--)
{
printf("%d", result[i]);
}
printf("\n");
}
main()
{
char input[ORSTR_SIZE]="-123";
int inputlen=0;
long numlong;
int numint;
/* int result[16]={0}; */
printf("the string is:");
puts(input);
inputlen=strlen(input);
if(IsValid(input,inputlen))
{
numint=atoi(buffer);
printf("string convert to integer is %d\n",numint);
IntToBin(numint);
}
}