如何在C ++中添加2个任意大小的整数? [英] How to add 2 arbitrarily sized integers in C++?

查看:121
本文介绍了如何在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上,您需要从 Windows端口的OpenSSL。

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

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

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