Thread: Possible to pack smaller data types into larger ones?

1. Possible to pack smaller data types into larger ones?

Hi,
I had a thought the other day, about packing two or more data type's into another larger data type. Then perform some addition/subraction operations on the larger data type, so you basically get two operations for the price of one.

Here is an example of what i mean:

short int a,b,c,d;
unsigned short int ab,cd;
long int e,f,result;

/* pack a & b into e */
/* pack c & d into f */

result = e + f;

/* unpack e and f, store in ab and cd */

Would ab now hold a+b, and cd hold c+d?

Say two chars were packed into a short...
12345678 | 12345678
----------------------------
00000001 | 00000001 dec 513 OR 1 and 1 as 2 chars
00000001 | 00000001 dec 513 OR 1 and 1 as 2 chars
00000010 | 00000010 dec 1026 OR 2 and 2 as two chars

I take it that the above would save an addition operation, instead of adding 2 chars to one another, then adding another 2 chars to one another.
Assuming that all this is possible, I would guess that there would be some sort of overhead involved in packing and unpacking, but how much?

I am quite new to C, so if I appear to have been on the crack pipe, please say.
I am just interested in the proof of concept of doing this, or ideally, any real world examples of it.

2. This is possible, and it might be worth the trouble if you do a significant number of operations with the packed data, so long as you don't overflow.

I don't know the MMX instructions by heart, but I've flipped through the manual for them and most of them seem to be designed to deal with packed integers of different sizes. If intel thinks it's worthwhile, it probably is :l

3. <kicks himself>
Well, I found that union's are able to do this very easily, so I shall experiment with them for a while.

Anybody think of any other ways?

4. If you are on the Intel/AMD plattform, have a look at the following webpages:

http://gcc.gnu.org/onlinedocs/gcc/X8...Functions.html
http://gcc.gnu.org/onlinedocs/gcc/Ve...r%20Extensions

example source code for SSE instructions:
Code:
```typedef float v4sf __attribute__ ((mode(V4SF)));

v4sf v1, v2;
float data[8], tmp[4];
/* fill array data */
...