Created
April 23, 2016 15:12
-
-
Save paiv/6d383d89561b6e0a96539875cc35d4a3 to your computer and use it in GitHub Desktop.
BigDigits C++ starter code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <bigd.h> // http://www.di-mgt.com.au/bigdigits.html | |
using namespace std; | |
namespace paiv | |
{ | |
typedef uint32_t u32; | |
class Big | |
{ | |
private: | |
BIGD bn; | |
public: | |
explicit Big() : bn(bdNew()) {} | |
Big(u32 x) : bn(bdNew()) { bdSetShort(bn, x); } | |
~Big() { if (bn) bdFree(&bn); bn = nullptr; } | |
Big(const Big& x) : bn(bdNew()) { bdSetEqual(bn, x.bn); } | |
Big(Big&& x) : bn(x.bn) { x.bn = nullptr; } | |
explicit operator BIGD() const { return bn; } | |
explicit operator u32() const { return bdToShort(bn); } | |
Big& operator+= (const Big& y) { bdAdd_s((BIGD)*this, (BIGD)*this, (BIGD)y); return *this; } | |
Big& operator-= (const Big& y) { bdSubtract_s((BIGD)*this, (BIGD)*this, (BIGD)y); return *this; } | |
Big& operator*= (const Big& y) { bdMultiply_s((BIGD)*this, (BIGD)*this, (BIGD)y); return *this; } | |
}; | |
inline bool operator== (const Big& x, const Big& y) { return bdCompare((BIGD)x, (BIGD)y) == 0; } | |
inline Big operator+ (Big x, const Big& y) { return x += y; } | |
inline Big operator- (Big x, const Big& y) { return x -= y; } | |
inline Big operator* (Big x, const Big& y) { return x *= y; } | |
inline Big pow (const Big& x, u32 n) { Big y; bdPower((BIGD)y, (BIGD)x, n); return y; } | |
ostream& operator<< (ostream& so, const Big& x) | |
{ | |
auto conv = (so.flags() & ios::hex) ? bdConvToHex : bdConvToDecimal; | |
size_t size = conv((BIGD)x, nullptr, 0) + 1; | |
string s(size, '\0'); | |
conv((BIGD)x, &s[0], size); | |
return so << s; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment