简体   繁体   中英

C++ shift left with big value

I'm wonder how to shift left value in C++. For example:

1 << 180

and I beleve that result of that should be:

1532495540865888858358347027150309183618739122183602176

(tested in python [1 << 180]);

Python supports arbitrary precision arithmetic, C++ does not.

Moreover, according to the Standard [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.

In order to use big integers in C++ you may use Boost library, which provides wrappers to different libraries with long arithmetic implementations:

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

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

Prints

1532495540865888858358347027150309183618739122183602176

You can do this using a std::bitset :

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

How useful that is depends on what you want to do with it. It can't be converted to a single build-in type because they are not large enough. But there are other potentially useful operations that can be performed on it.

In C++ (as in C) a left-shift by a value larger than the number of bits in the shifted operand's type actually gives undefined behaviour.

In this case you are shifting an int value which is most likely 32 bits in size left by a value greater than 32, hence, the behaviour is undefined.

If you need to deal with integers larger than the word size on your machine, you're probably going to need to use a library. GMP is one option.

Integers (or longs) are stored in 32bits and can therefore not be shifted 180. If you need the exact value, try to write/download a class that manages big integers. Otherwise, use a double and call pow(2,180). It has an accuracy 0f 15 digits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM