handling and comparing large number initially in string format

Feb 16, 2014 at 8:06pm
Hi guys,

suppose i have a very large number stored as a string, say

std::string str = "1000000000000000000000000000000000001";

and i use std::stringstream to convert it to int like this

1
2
3
std::stringstream ss(str);
uint64_t i;
ss >> i;

then i would be maxed out right. so how would one practically handle things like comparison of two such numbers.

I could think of 2 approaches
1) I can compare the numbers character by character.
2) I can put the results of ss >> i; into an array then compare each element of array

would there be any other methods??
Feb 16, 2014 at 8:15pm
You need to use a bigint library.

For example, this was the first hit in the search I just did.
https://mattmccutchen.net/bigint/
Feb 17, 2014 at 7:59am
Seems to be lot of overhead for just comparison, i will not need any other arithmetic operations, the only thing i require is to compare.
Feb 17, 2014 at 9:03am
It is a new concrete type, so you should implement a class that supports the relevant operations.

If all you need is comparison, then just implement operator< and choose an implementation that easily supports that.

For example, it might be sufficient to keep the implementation as decimal characters held in a string. The less than operator is easy to implement with a combination of string length and where necessary comparisons of greater significant characters.

It doesn't cost anything in time or space to do it this way, you'll have to write the comparison anyway. That is, the generated code won't be any larger or slower.

The whole point of using a class is that it's used in a standard way and can extanded/reimplemented with touching the code that uses it.

Also, if you decide to use someone's bigint class, it should just plug in without any code change on your part apart from setting up the definition.
Last edited on Feb 17, 2014 at 9:04am
Feb 17, 2014 at 9:23am
Thanks for the input :)
Topic archived. No new replies allowed.