C++ 大值左移

C++ shift left with big value

我想知道如何在 C++ 中左移值。 例如:

1 << 180

我相信结果应该是:

1532495540865888858358347027150309183618739122183602176

(在 python [1 << 180] 中测试);

整数(或长整数)以 32 位存储,因此不能移位 180。 如果您需要确切的值,请尝试 write/download 管理大整数的 class。 否则,使用 double 并调用 pow(2,180)。它的精度为 0f 15 位

在 C++ 中(如在 C 中)左移一个大于移位操作数类型中的位数的值实际上会产生未定义的行为。

在这种情况下,您正在移动一个 int 值,该值很可能是 32 位大小,左边的值大于 32,因此,行为是未定义的。

如果您需要处理大于机器字长的整数,您可能需要使用一个库。 GMP 是一种选择。

Python支持任意精度运算,C++不支持。

此外,根据标准[expr.shift]:

The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

为了在 C++ 中使用大整数,您可以使用 Boost 库,它为具有长算术实现的不同库提供包装器:

#include <boost/multiprecision/gmp.hpp>
#include <iostream>

int main()
{
    boost::multiprecision::mpz_int one(1);
    std::cout << (one << 180) << std::endl;
    return 0;
}

版画

1532495540865888858358347027150309183618739122183602176

您可以使用 std::bitset:

std::bitset<200> bits = 1; // 200 bits long
bits <<= 180;

它的用处取决于你想用它做什么。它不能转换为单一的内置类型,因为它们不够大。但是还有其他可以对其执行的潜在有用的操作。