我想在C ++中添加2个任意大小的整数。我该怎么做呢? [英] I would like to add 2 arbitrarily sized integers in C++. How can I go about doing this?

查看:241
本文介绍了我想在C ++中添加2个任意大小的整数。我该怎么做呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中添加2个任意大小的整数。

I would like to add 2 arbitrarily sized integers in C++. How can I go about doing this?

推荐答案

这里是一个示例,显示如何使用 OpenSSL bignum 实现任意精度算术。我的例子是2 64 + 2 65 。我使用的是Linux。

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

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.

g++ bignum.cpp -o bignum -lcrypto

或下载OpenSSL源并构建静态库 libcrypto.a 并静态链接。

Or download the OpenSSL source and build the static library libcrypto.a and link with it statically.

g++ bignum.cpp -o bignum -I./openssl-1.0.0/include ./openssl-1.0.0/libcrypto.a

在Windows上,您需要从OpenSSL的 Windows端口进行安装。

On Windows, you'll need to install from the Windows port of OpenSSL.

这篇关于我想在C ++中添加2个任意大小的整数。我该怎么做呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆