# how achieve split of unsigned4 into two signed2's using bit-wise instead of union?

• 10-31-2008
6tr6tr
how achieve split of unsigned4 into two signed2's using bit-wise instead of union?
I know this code is completely valid but in the interest of learning, how would I achieve the same thing as below using bitwise operations on the unsigned4 value instead of the union "trick"?

Code:

```void value(unsigned4 v) {     union     {         struct         {         signed2 left;         signed2 right;         } split;           unsigned4 combined;       } trick;       //Set the base value     trick.combined = v;       //"Split" the value into left and right values     left = trick.split.left;     right = trick.split.right; }```
• 10-31-2008
master5001
What are signed2 and unsigned4?
• 10-31-2008
Waterbottle
Code:

```left = (v & 0xFFFF0000) >> 16; right = (v & 0x0000FFFF);```
perhaps?
• 10-31-2008
6tr6tr
Quote:

Originally Posted by master5001
What are signed2 and unsigned4?

As best I can gather from the code:

unsigned4 = unsigned int
signed2 = signed short int
• 10-31-2008
matsp
Quote:

Originally Posted by Waterbottle
Code:

```left = (v & 0xFFFF0000) >> 16; right = (v & 0x0000FFFF);```
perhaps?

It is sometimes better to do
Code:

```left = (v  >> 16) & 0x0000FFFF; right = v & 0x0000FFFF;```
because using smaller constants and put the and operation last makes it possible for the compiler to figure out that those operations are meaningless if the processor has native support for 16-bit integers.

--
Mats
• 10-31-2008
iMalc
Quote:

Originally Posted by matsp
It is sometimes better to do
Code:

```left = (v  >> 16) & 0x0000FFFF; right = v & 0x0000FFFF;```
because using smaller constants and put the and operation last makes it possible for the compiler to figure out that those operations are meaningless if the processor has native support for 16-bit integers.

Yeah I recommend always doing a right shift before the masking. On CISC systems, it takes fewer bytes of compiled code to store the smaller constant in the compiled instructions. (assuming it isn't exactly the case matsp mentioned)

Nothing wrong either way of course, it's just a micro optimisation.