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

1. ## 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;
}```

2. What are signed2 and unsigned4?

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

4. Originally Posted by master5001
What are signed2 and unsigned4?
As best I can gather from the code:

unsigned4 = unsigned int
signed2 = signed short int

5. 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

6. 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.