简体   繁体   中英

C++ arbitrary length integers

In C++, is it possible to define arbitrary length integers?

So instead of having to use uint64_t for anything in between 33 and 64 bit, I could define my own 34 bit, 36 bit, etc., integers.

The compiler has its own types like you did mention. long (32 bit on most platforms) and long long (64 bit on most platforms). If you need support for larger integers, you could use different libraries which limit the size of the integer to the size of your memory.

Libraries:

As you are living in C++ world use https://gmplib.org/

Should do the trick

For computation it would give you no advantage because today processors are optimized for either 32-bit or 64-bit arithmetic.

If you need them for size problems instead it could make sense to define your own container of n-bit numbers and this could be easily coded.

Even more general could be a container for mod-n numbers (ie for numbers from 0 to n-1, not necessarily for modulo with an exact power of two). For this an easy solution (but not space optimal) could be based on the largest power of n that fits in a 64-bit integer (eg you can pack 22 numbers between 0 and 6 into a single number between 0 and 2**64-1).

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