user3302398
user3302398

Reputation: 13

Make your own data range in c++

I want to have a data variable which will be an integer and its range will be from 0 - 1.000.000. For example normal int variables can store numbers from -2,147,483,648 to 2,147,483,647. I want the new data type to have less range so it can have LESS SIZE.

If there is a way to do that please let me know?

Upvotes: 1

Views: 1739

Answers (3)

Bill Lynch
Bill Lynch

Reputation: 81926

So, there's no true good answer to this problem. Here are a few thoughts though:

  1. If you're talking about an array of these 20 bit values, then perhaps the answers at this question will be helpful: Bit packing of array of integers

  2. On the other hand, perhaps we are talking about an object, that has 3 int20_ts in it, and you'd like it to take up less space than it would normally. In that case, we could use a bitfield.

    struct object {
        int a : 20;
        int b : 20;
        int c : 20;
    } __attribute__((__packed__));
    
    printf("sizeof object: %d\n", sizeof(struct object));
    

    This code will probably print 8, signifying that it is using 8 bytes of space, not the 12 that you would normally expect.

Upvotes: 2

HelloWorld123456789
HelloWorld123456789

Reputation: 5359

You can only have data types to be multiple of 8 bits. This is because, otherwise that data type won't be addressable. Imagine a pointer to a 5 bit data. That won't exist.

Upvotes: 0

TypeIA
TypeIA

Reputation: 17250

There isn't; you can't specify arbitrary ranges for variables like this in C++.

You need 20 bits to store 1,000,000 different values, so using a 32-bit integer is the best you can do without creating a custom data type (even then you'd only be saving 1 byte at 24 bits, since you can't allocate less than 8 bits).

As for enforcing the range of values, you could do that with a custom class, but I assume your goal isn't the validation but the size reduction.

Upvotes: 2

Related Questions