Java Array Merge arrayMerge16bit(byte[] sourceArray, int sourceStart, byte[] destinationArray, int destinationStart, int length)

Here you can find the source of arrayMerge16bit(byte[] sourceArray, int sourceStart, byte[] destinationArray, int destinationStart, int length)

Description

Merges two byte arrays -- source and destination -- together by summing field-wise where a field is a 16bit word, which is two of these array bytes.

License

Open Source License

Declaration

public static void arrayMerge16bit(byte[] sourceArray, int sourceStart, byte[] destinationArray,
        int destinationStart, int length) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/* www.  j  a v a 2  s.c om*/
     * Merges two byte arrays -- source and destination -- together by summing field-wise where a field is a 16bit word, which is
     * two of these array bytes. The result is written into the destination array.
     */
    public static void arrayMerge16bit(byte[] sourceArray, int sourceStart, byte[] destinationArray,
            int destinationStart, int length) {

        if (sourceArray.length - sourceStart < length || destinationArray.length - destinationStart < length) {
            throw new IllegalStateException("Length too large for input arrays.");
        }

        for (int i = 0; i < length; i = i + 2) {

            int srcValue = (sourceArray[sourceStart + i] & 0xFF) | (sourceArray[sourceStart + i + 1] << 8);
            int dstValue = (destinationArray[destinationStart + i] & 0xFF)
                    | (destinationArray[destinationStart + i + 1] << 8);

            int sum = srcValue + dstValue;

            if (32768 <= sum) {
                sum = 32768;
            }

            if (sum <= -32767) {
                sum = -32767;
            }

            destinationArray[destinationStart + i] = (byte) (sum & 0xFF);
            destinationArray[destinationStart + i + 1] = (byte) (sum >> 8);
        }
    }
}

Related

  1. concat(double[] merged, double[] is)
  2. merge( final Item[] values, final Item[] auxiliary, final int first, final int middle, final int last)
  3. merge(byte[] a, byte[] b)
  4. merge(byte[] array1, byte[] array2)