简体   繁体   中英

Fixed-size number in C++

So, I'm creating a library that requires fixed-size numbers (not as in uint32_t but custom sizes). Therefore, I assumed I could do something similar to this:

typedef unsigned int custom_size_t:524272; // it's 65535 bytes as max value

However, when I tried this, my IDE (CLion 2020.1) gave me an error: Expected unqualified-id . Then, I try to compile it. It gives me a bucketload of errors; mainly, it gives me the error expected initializer before ':' token .

I've tried moving the :524272 to the unsigned int part (after), without any expectations of success. Sure enough, I was right. I've already searched for a solution, but they all refer to sizes such as uint32_t and alike.

How would I go about this? Oh, and, for reference, this is my code (with a bit obfuscation):

typedef unsigned int custom_size_t_1:524288;
typedef unsigned int custom_size_t_2:524272;

// ... other code ...

No such syntax exists in C++ for integer types of arbitrary sizes.

Only the sizes of fundamental integer types char , short , int , long and long long are available, which are always powers of two bytes in size. The exact width integers are aliases of these types. Implementations may provide other integer types as an extension, but only these are guaranteed to exist by the standard.

What you can do is define a custom class that behaves like an integer through overloaded operators, but is implemented internally as an array of bytes (array of integers is faster, but then the size must of course be multiple of the integer type).

This is concept generally called arbitrary precision or multiple precision arithmetic.


There is a standard proposal n2472 to add arbitrary width integer types to the language (with different syntax than what you propose). It was recently implemented in Clang as a language extension.

If you are looking for integers to be used, you are limited to what's available in <cstdint> , which was introduced in C++11

Namely, int8_t, int16_t, etc. https://en.cppreference.com/w/cpp/types/integer

If you want to manipulate numbers by their bits, you can use bitsets

If you are looking for are looking to perform math operations with certain precision or larger numbers you can use an external library, such as:

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