Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Custom Data Type for Huge Numbers (http://www.go4expert.com/forums/custom-data-type-huge-t12827/)

rivaskh 10Aug2008 00:29

Custom Data Type for Huge Numbers
 
Hi,

Is there any way that I can do a following initialization?

DataType abc = 22222222222222222222222;

where the value is a huge number larger than 2^32.

erislover 10Aug2008 03:50

Re: Custom Data Type for Huge Numbers
 
Probably not. But check out gmplib.org for a library that could help you.

erislover 10Aug2008 04:04

Re: Custom Data Type for Huge Numbers
 
Well, by "probably not" I'm assuming you need something larger than 64 bits, available on every 32-bit system I'm aware of. If you're working in embedded systems where 32 bits is already your largest built-in data type, then you must code up your own functions and declarations to deal with larger numbers. This is much easier in C++ than C because of operator overloading. If you are working with C++ then google will help you find plenty of good resources for hand-rolling what you need, if you don't want to use GMP.

xpi0t0s 10Aug2008 13:24

Re: Custom Data Type for Huge Numbers
 
No, because 22222222222222222222222 is an invalid number and will be picked up by the compiler as an error.
However you could encode the number differently, for example using strings:
DataType abc = "22222222222222222222222";

rivaskh 10Aug2008 21:56

Re: Custom Data Type for Huge Numbers
 
True... I was wondering if I could create a a class that coupled a lot of integers together to form a super integer that could take values higher than 32 bit with it having the same operations as a primitive integer type. This way, I could use it in place of unsigned int and still retain my code without too much change.

xpi0t0s 10Aug2008 22:26

Re: Custom Data Type for Huge Numbers
 
Yes of course, that's the whole point of operator overloading in C++. In C++ you can fairly easily write something like
Code:

MyBigNumCls num1(23,75,62); // a constructor that takes 3 integers
MyBigNumCls num2(49,11,51);
MyBigNumCls result=num1+num2;

So num1(23,75,62) could represent 23<<64 | 75<<32 | 62 and it's up to you how to store it, as three integers if you like. With the above code result, assuming you've defined MyBigNumCls::operator +(), would then represent (23+49)<<64 | (75+11)<<32 | (62+51)

This is easy to do; have a go and see how far you get. For multiplication and division just look back to how you used to do it at school on paper then implement that algorithm.


All times are GMT +5.5. The time now is 07:05.