这个是我写的,敬请指教!
#include "Stdio.h"
#include "Conio.h"
#include "ctype.h"
#define N 20
char str[N];
unsigned long int power(int base,int exp)
{
int i;
unsigned long int mid=1;
for(i=0;i<exp;i++)
{
mid*=base;
}
return mid;
}
long chtolong(char *ps)
{
unsigned long int ch;
int len, i;
long digit=0;
char *s=ps;
len=strlen(s);
for(i=0;i<len;i++,s++)
{
if(isalpha(*s))
{
ch=tolower(*s)-87;
digit+=power(16,len-1-i)*ch;
}
else if(isdigit(*s))
{
ch=*s-'0';
digit+=power(16,len-1-i)*ch;
}
else if(*s=='+'||*s=='-')
{
;
/*printf("%c",*s);*/
}
else
{
printf("\nInput error!!!\n");
return 0;
}
}
if(*ps=='-')
digit=-digit;
return digit;
}
char *longtoch(long int n)
{
int i=1,j, k;
char ch;
str[0]=0;
if(n<0)
{
str[0]='-';
n=-n;
}
while(n!=0)
{
if(n%16>=10)
str[i++]=n%16+87;
else
str[i++]=n%16+48;
n/=16;
}
j=(i-1)/2;
for(k=1;k<=j;k++)
{
ch=str[k];
str[k]=str[i-k];
str[i-k]=ch;
}
return str;
}
int main(void)
{
long int in, out;
int i;
printf("\nInput a string:\n");
gets(str);
out=chtolong(str);
printf("\nOutput a long int from string:%ld\n",out);
getch();
printf("\nInput a long int digit:\n");
scanf("%ld",&in);
longtoch(in);
printf("\nOutput a string from a long int :%s\n",str);
getch();
return 0;
}