Question: I need to combine two Bytes into one int value.

I receive from my camera a 16bit Image were two successive bytes have the intensity value of one pixel. My goal is to combine these two bytes into one "int" vale. 

I manage to do this using the following code:

```
for (int i = 0; i < VectorLength * 2; i = i + 2)
{
  NewImageVector[ImagePointer] = ((int)(buffer.Array[i + 1]) << 8) | ((int)(buffer.Array[i]));      
  ImagePointer++;
}

```

My image is 1280\*960 so VectorLength==1228800 and the incomming buffer size is 2\*1228800=2457600 elements...

Is there any way that I can speed this up?
Maybe there is another way so I don't need to use a for-loop.

Thank you

Answer: 
You could use the equivalent to the union of c. Im not sure if faster, but more elegant:

```
[StructLayout(LayoutKind.Explicit)]
struct byte_array
{
  [FieldOffset(0)]
  public byte byte1;

  [FieldOffset(1)]
  public byte byte2;

  [FieldOffset(0)]
  public short int0;
}

```

use it like this:

```
byte_array ba = new byte_array();

//insert the two bytes
ba.byte1 = (byte)(buffer.Array[i]);
ba.byte2 = (byte)(buffer.Array[i + 1]);

//get the integer
NewImageVector[ImagePointer] = ba.int1;

```

You can fill your two bytes and use the int. To find the faster way take the StopWatch-Class and compare the two ways like this:

```
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

//The code

stopWatch.Stop();
MessageBox.Show(stopWatch.ElapsedTicks.ToString()); //Or milliseconds ,...

```
You can achieve a small performance increase by using unsafe pointers to iterate the arrays. The following code assumes that `source` is the input byte array (`buffer.Array` in your case). It also assumes that `source` has an even number of elements. In production code you would obviously have to check these things.

```
int[] output = new int[source.Length / 2];
fixed (byte* pSource = source)
fixed (int* pDestination = output)
{
    byte* sourceIterator = pSource;
    int* destIterator = pDestination;
    for (int i = 0; i < output.Length; i++)
    {
        (*destIterator) = ((*sourceIterator) | (*(sourceIterator + 1) << 8));
        destIterator++;
        sourceIterator += 2;
    }
}
return output;

```