发信人: earth_walker(戒定慧)
整理人: yangcs(2004-10-14 14:22:35), 站内信件
|
#include "based-int.h"
typedef struct rec{
int base;
char* S;
} REC;
//////////////////////////////
int power(a, p)
//tested
int a; int p;
{
int product=1,counter;
for (counter=p; counter>=1; counter--) product *= a;
return product;
}
int asctoint (c)
//tested
int c;
{
if ((c>=48)&&(c<=57)) return c-48;
if ((c>=65)&&(c<=90)) return c-65+10;
if ((c>=97)&&(c<=122)) return c-97+10;
}
int inttoasc (i)
//tested
int i;
{
if ((i>=0)&&(i<=9)) return i+48;
if ((i>=10)&&(i<=35)) return i-10+65;
}
char* tostringtailrecur(I, bas, temp)
//tested
int I, bas; char* temp;
{
char *pc;
if (I==0) return temp;
else{
pc = (char*)malloc(sizeof(char));
*pc = (char)(inttoasc(I % bas));*(pc+1)=*"\0";
strcat(pc, temp);
free (temp);
I=I/bas;
return tostringtailrecur(I, bas, pc);
}
}
//////////////////////////////////
int outrangebasetest(b)
//tested
int b;
{
if ((b>=2)&&(b<=36)) return 1;
else{
printf("the base must be between or equal to 2 and 36.\n");
exit(0);
}
}
int basetoosmalltest(S, b)
//tested
char* S; int b;
{
int counter, length=strlen(S);
char *pc;
for (counter=0; counter<=(length-1); counter++) {
pc=S+counter;
if (b<=asctoint((int)(*pc))){
printf("the base must be lager than the integer represented by largest digit.\n");
exit (0);
}
}
return 1;
}
//////////////////////////////////
int getbase (B)
//tested
based B;
{
return B->base;
}
int todec (B)
//tested
based B;
{
char *pc;
int counter,length=strlen(B->S),result=0;
for (counter=1; counter<=length; counter++) {
pc=(char*)malloc(sizeof(char));
strncpy ( pc, (B->S)+(length-counter), 1 );
result = result + asctoint(toascii(*pc)) * power(B->base, counter-1);
}
return result;
}
based tobased (I, bas)
//tested
int I, bas;
{
based temp;
char* result="\0";
outrangebasetest (bas);
temp = (based)malloc(sizeof(*temp));
temp->base = bas;
temp->S= tostringtailrecur(I, bas, result);
return temp;
}
based changebase (B, bas)
//tested
based B; int bas;
{
int i;
i=todec(B);
return tobased(i ,bas);
}
based makebased (S, b)
//tested
char* S; int b;
{
based temp;
outrangebasetest(b);
basetoosmalltest(S,b);
temp=(based)malloc(sizeof(struct rec));
(temp->base)=b;
temp->S=(char*)malloc(sizeof(char));
strcpy(temp->S,S);
strcat(temp->S,"\0");
return temp;
}
char* tostring (B)
//tested
based B;
{
char* pc;
pc=(char*)malloc(sizeof(char));
strcpy (pc, B->S);
return pc;
}
based copybased (B)
//tested
based B;
{
return makebased(tostring(B),getbase(B));
}
---- 圣菩提心极珍贵,诸未生者令生起,
令已发起不衰退,辗转增上恒滋长。
|
|