Main Page   Class Hierarchy   Data Structures   File List   Data Fields   Globals  

bigint.C

Go to the documentation of this file.
00001 #include <stdio.h>
00002 #include <string.h>
00003 #include "BigInt.H"
00004 
00005 // The BigInt(const char*) constructor.
00006 BigInt::BigInt(const char* digitString) {
00007   int n = strlen(digitString);
00008   if (n != 0) {
00009     digits = new char[ndigits=n];
00010     char* p = digits;
00011     const char* q = &digitString[n];
00012     while (n--) *p++ = *--q - '0';
00013   }
00014   else {
00015     digits = new char[ndigits=1];
00016     digits[0] = 0;
00017   }
00018 }
00019 
00020 // The BigInt(int) constructor.
00021 BigInt::BigInt(int n) {
00022   char d[3*sizeof(int)+1];
00023   char* dp = d;
00024   ndigits = 0;
00025   do {
00026     *dp++ = n%10;
00027     n /= 10;
00028     ndigits++;
00029   } while (n > 0);
00030   digits = new char[ndigits];
00031   register int i;
00032   for (i=0; i<ndigits; i++) digits[i] = d[i];
00033 }
00034 
00035 // The BinInt(const&) constructor.
00036 BigInt::BigInt(const BigInt& n) {
00037   int i = n.ndigits;
00038   digits = new char[ndigits=i];
00039   char* p = digits;
00040   char* q = n.digits;
00041   while (i--) *p++ = *q++;
00042 }
00043 
00044 // The BigInt assignment operator.
00045 void BigInt::operator=(const BigInt& n) {
00046   if (this==&n) return;
00047   unsigned i = n.ndigits;
00048   digits = new char[ndigits=i];
00049   char* p = digits;
00050   char* q = n.digits;
00051   while (i--) *p++ = *q++;
00052 }
00053 
00054 
00055 
00056 // The BigInt addition Operator.
00057 BigInt BigInt::operator+(const BigInt& n) {
00058   int maxDigits = (ndigits>n.ndigits ? ndigits : n.ndigits) + 1;
00059   char* sumPtr = new char[maxDigits];
00060   BigInt sum(sumPtr, maxDigits);
00061   DigitStream a(*this);
00062   DigitStream b(n);
00063   int i = maxDigits;
00064   int carry = 0;
00065   while (i--) {
00066     *sumPtr = (a++) + (b++) + carry;
00067     if (*sumPtr>9) {
00068       carry = 1;
00069       *sumPtr -= 10;
00070     }
00071     else carry = 0;
00072     sumPtr++;
00073   }
00074   return sum;
00075 }
00076 
00077 // The BigInt::print member function.
00078 void BigInt::print() {
00079   int i;
00080   for (i=ndigits-1; i>=0; i--) printf( "%d", digits[i]);
00081 }
00082 

Generated at Sun Feb 24 09:56:55 2002 for STARLAB by doxygen1.2.6 written by Dimitri van Heesch, © 1997-2001