I would like to add 2 arbitrarily sized integers in C++. How can I go about doing this?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Here's an example showing how to use the OpenSSL bignum implementation for arbitrary-precision arithmetic. My example does 264 + 265. I'm using Linux.
It produces this output:
You need to have OpenSSL installed with the development libraries. If you have Linux, install the development library from your package manager and link with
libcrypto.so
.Or download the OpenSSL source and build the static library
libcrypto.a
and link with it statically.On Windows, you'll need to install from the Windows port of OpenSSL.
Using the
+
operator?If you want to perform the multi-precision math yourself, then I suggest you take a look at Donald Knuth's Art of Computer Programming. I believe Volume II, Seminumerical Algorithms, Chapter 4, Multiple Precision Arithmetic, is what you are interested in. Knuth gives you all the gory details.
Handling large numbers in C++? also provides a reference to an interesting paper. You should probably read it if you are rolling your own implementation. (Other similar questions lack the reference. Thanks to @herohuyongtao for providing it).
In addition to @indiv answer of using OpenSSL in C, you can use Botan or Crypto++. Both are C++ libraries, and both are about as old as OpenSSL. I'm surprised answers were not provided for them considering your question is tagged C++.
If you have C++11 or
unique_ptr
, then you can use them for the OpenSSL C code.unique_ptr
really tidies things up. An example is given below.Botan
Here is the program:
And building from the library's directory (expediency):
Crypto++
Here is the program:
And building from the library's directory (expediency):
OpenSSL
Here is the program for C++ and OpenSSL. The
BN_obj
"has a"BIGNUM
, and it usesunique_ptr
to manage the resources.And building from the library's directory (expediency):