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.
#include <cstdio>
#include <openssl/crypto.h>
#include <openssl/bn.h>
int main(int argc, char *argv[])
{
static const char num1[] = "18446744073709551616";
static const char num2[] = "36893488147419103232";
BIGNUM *bn1 = NULL;
BIGNUM *bn2 = NULL;
BN_CTX *ctx = BN_CTX_new();
BN_dec2bn(&bn1, num1); // convert the string to BIGNUM
BN_dec2bn(&bn2, num2);
BN_add(bn1, bn1, bn2); // bn1 = bn1 + bn2
char *result_str = BN_bn2dec(bn1); // convert the BIGNUM back to string
printf("%s + %s = %s\n", num1, num2, result_str);
OPENSSL_free(result_str);
BN_free(bn1);
BN_free(bn2);
BN_CTX_free(ctx);
return 0;
}
它产生以下输出:
18446744073709551616 + 36893488147419103232 = 55340232221128654848
您需要随开发库一起安装 OpenSSL。如果您有 Linux,请从包管理器安装开发库并链接到libcrypto.so
.
g++ bignum.cpp -o bignum -lcrypto
或者下载 OpenSSL 源代码并构建静态库libcrypto.a
并与其静态链接。
g++ bignum.cpp -o bignum -I./openssl-1.0.0/include ./openssl-1.0.0/libcrypto.a
在 Windows 上,您需要从Windows端口OpenSSL 的。