1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • do you only need to store them or will you do some arithmetic ? – Michael M. Feb 12 '14 at 16:03
  • An integer type that has less range is far, far easier than one that has less range *and* has less size. You understand that your 0 to 1 million value would require 63% of the size of the standard integer, and would be much much slower? – Yakk - Adam Nevraumont Feb 12 '14 at 16:15

3 Answers3

2

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.

TypeIA
  • 16,916
  • 1
  • 38
  • 52
2

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.

Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

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.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33