Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 2.5 bytes (20-bit) integer

I know it's ridiculous, but I need it for storage optimization. Is there any good way to implement it in C++?

It has to be flexible enough so that I can use it as a normal data type e.g Vector< int20 >, operator overloading, etc..

like image 340
w00d Avatar asked Sep 16 '10 09:09

w00d


People also ask

Is int always 32 bits in C?

int is always 32 bits wide. sizeof(T) represents the number of 8-bit bytes (octets) needed to store a variable of type T .

Why integer is 4 bytes in C?

So the reason why you are seeing an int as 4 bytes (32 bits), is because the code is compiled to be executed efficiently by a 32-bit CPU. If the same code were compiled for a 16-bit CPU the int may be 16 bits, and on a 64-bit CPU it may be 64 bits.

Is an integer 2 bytes?

Most of the textbooks say integer variables occupy 2 bytes.


1 Answers

If storage is your main concern, I suspect you need quite a few 20-bit variables. How about storing them in pairs? You could create a class representing two such variables and store them in 2.5+2.5 = 5 bytes.

To access the variables conveniently you could override the []-operator so you could write:

int fst = pair[0];
int snd = pair[1];

Since you may want to allow for manipulations such as

pair[1] += 5;

you would not want to return a copy of the backing bytes, but a reference. However, you can't return a direct reference to the backing bytes (since it would mess up it's neighboring value), so you'd actually need to return a proxy for the backing bytes (which in turn has a reference to the backing bytes) and let the proxy overload the relevant operators.

As a metter of fact, as @Tony suggest, you could generalize this to have a general container holding N such 20-bit variables.

(I've done this myself in a specialization of a vector for efficient storage of booleans (as single bits).)

like image 62
aioobe Avatar answered Oct 07 '22 12:10

aioobe