Large Numbers - The User Interface
(Page 2 of 5 )
The class we are creating is going to hold large numbers. That is, to be more specific, a really long sequence of one digit numbers accompanied by its sign, and obviously we also need to differentiate between the integer and real part of the number. The sign should be also known at all times.
So the question is how to store the numbers - specifically, a one digit number. That's 10 options (0, 1, 2... 8, 9). The memory blocks in computers are divided into bytes. One byte equals eight bits. On one byte we can store in the binary file system 2 ^ 8 = 256. That's from 0 to 255.
Therefore, we've just found out that a byte is entirely enough for us, though we are also wasting some memory if we choose to store them in a byte. Half of it (2^ 4 = 16) could be enough, but in C there exists no such variable that's stored in four bits.
All in all, we'll stick with the eight bit plan following the principle of keeping it as simple as possible, especially to make the code easier to comprehend. However, if you're feeling brave then you should know that there exists a solution to this. This is accomplished by splitting the char into two section using bit fields. You will gain some extra memory usage improvement, but you will lose some speed and have more difficulty finding and working with a specific item. The bottom line is that I used the following design.
For the dynamic allocation issue in the memory I've used STL. The obvious option is std::vector<char> that is the same as std::string. We are signaling the place of the "." (or "," in some countries) with the whole member, so we don't need to store that character in the number, which will only contain all the number sequence.
private:
std::string number; // contains the number
unsigned long int whole;// shows the whole part
unsigned long int all; // the length of the number
short int sign; // the sign of the number
Next: File Input Lesson >>
More C++ Articles
More By Gabor Bernat