Java Array Shorten toShortArray(byte[] data)

Here you can find the source of toShortArray(byte[] data)

Description

to Short Array

License

Open Source License

Declaration

public static short[] toShortArray(byte[] data) 

Method Source Code

//package com.java2s;
/*/*from   ww w .  j  ava  2  s  .c om*/
 * Copyright (C) 2014 Jesse Caulfield 
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    public static short[] toShortArray(byte[] data) {
        if ((data == null) || (data.length % 2 != 0)) {
            return null;
        }
        short[] shts = new short[data.length / 2];
        for (int i = 0; i < shts.length; i++) {
            shts[i] = toShort(new byte[] { data[(i * 2)], data[(i * 2) + 1] });
        }
        return shts;
    }

    /**
     * Convert 2 bytes into a short.
     * <p>
     * This converts the 2 bytes into a short. The msb will be the high byte (8
     * bits) of the short, and the lsb will be the low byte (8 bits) of the short.
     *
     * @param msb The Most Significant Byte.
     * @param lsb The Least Significant Byte.
     * @return A short representing the bytes.
     */
    public static short toShort(byte msb, byte lsb) {
        return (short) ((0xff00 & (short) (msb << 8)) | (0x00ff & (short) lsb));
    }

    public static short toShort(byte[] data) {
        if ((data == null) || (data.length != 2)) {
            return 0x0;
        }
        return (short) ((0xff & data[0]) << 8 | (0xff & data[1]));
    }
}

Related

  1. toShortArray(double[][] array)
  2. toShortArray(final byte[] array)
  3. toShortArray(long value, int length)
  4. toShortArray(Number[] array)