假设我在c++
中输入了一个很长的字符串编号。我们必须对它进行数字操作。我们需要将其转换为integer
或任何可能的操作方式,那是什么?如何将大数字字符串转换为C++中的整数?
string s="12131313123123213213123213213211312321321321312321213123213213";
假设我在c++
中输入了一个很长的字符串编号。我们必须对它进行数字操作。我们需要将其转换为integer
或任何可能的操作方式,那是什么?如何将大数字字符串转换为C++中的整数?
string s="12131313123123213213123213213211312321321321312321213123213213";
如果字符串包含小于std::numeric_limits<uint64_t>::max()
号码,然后std::stoull()
是最好的意见。
unsigned long long = std::stoull(s);
C++11
以后。
你最好的办法是使用大量的计算库。
一个最好的在那里是一个有用的功能GNU Multiple Precision Arithmetic Library
实例为您解决问题::
Function: int mpz_set_str (mpz_t rop, const char *str, int base)
设置ROP从str中的值,一个空值在基地 基地终止的C字符串。字符串中允许有空格,并且简单地被忽略。
基底可能会发生变化,从2到62,或者如果碱是0,则使用前导 字符:0X和0X十六进制,0B 0B和二进制, 0为八进制或十进制否则。
对于最多为36的基数,忽略情况;大写和小写字母 具有相同的值。对于第37至62位,大写字母代表 通常的10..35,而小写字母代表36..61。
如果整个字符串是基于 base的有效数字,则此函数返回0。否则它返回-1。
文档:https://gmplib.org/manual/Assigning-Integers.html#Assigning-Integers
看起来你要处理的数字的方式来大任何标准整数类型,所以只是“转换”它不会给你很多。你有两个选择:(!强烈推荐)
使用大整数库象例如gmp
。这样的库通常还提供解析和格式化大数字的功能。
自己实现你的大数字,你可以例如使用阵列uintmax_t
来存储它们。你将不得不实施你可能需要的各种算法,这不是一件容易的事情。为了解析这个数字,你可以使用一个反转的double dabble实现。举个例子,这里有一些我前一段时间用C编写的代码,你可以使用原样,但是你需要提供一些帮助函数,你可能想用C++工具来重写它,比如std::string
并替换struct
这里使用一个std::vector
- 它只是在这里记录的概念
typedef struct hugeint
{
size_t s; // number of used elements in array e
size_t n; // number of total elements in array e
uintmax_t e[];
} hugeint;
hugeint *hugeint_parse(const char *str)
{
char *buf;
// allocate and initialize:
hugeint *result = hugeint_create();
// this is just a helper function copying all numeric characters
// to a freshly allocated buffer:
size_t bcdsize = copyNum(&buf, str);
if (!bcdsize) return result;
size_t scanstart = 0;
size_t n = 0;
size_t i;
uintmax_t mask = 1;
for (i = 0; i < bcdsize; ++i) buf[i] -= '0';
while (scanstart < bcdsize)
{
if (buf[bcdsize - 1] & 1) result->e[n] |= mask;
mask <<= 1;
if (!mask)
{
mask = 1;
// this function increases the storage size of the flexible array member:
if (++n == result->n) result = hugeint_scale(result, result->n + 1);
}
for (i = bcdsize - 1; i > scanstart; --i)
{
buf[i] >>= 1;
if (buf[i-1] & 1) buf[i] |= 8;
}
buf[scanstart] >>= 1;
while (scanstart < bcdsize && !buf[scanstart]) ++scanstart;
for (i = scanstart; i < bcdsize; ++i)
{
if (buf[i] > 7) buf[i] -= 3;
}
}
free(buf);
return result;
}
鉴于这样的数量不能满足“常规”整数类型,你必须要么重写你需要自己的操作,或者使用bignum图书馆。 –