Java Byte Array to Short bytesToShort(final byte[] aBuffer, final int aPos)

Here you can find the source of bytesToShort(final byte[] aBuffer, final int aPos)

Description

bytes To Short

License

Open Source License

Parameter

Parameter Description
aBuffer a parameter
aPos a parameter

Exception

Parameter Description
IllegalArgumentException an exception

Declaration

public static short bytesToShort(final byte[] aBuffer, final int aPos)
        throws IllegalArgumentException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011 www.isandlatech.com (www.isandlatech.com)
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from  ww  w. j  av  a 2 s. c o  m
 *    ogattaz (isandlaTech) - initial API and implementation
 *******************************************************************************/

public class Main {
    public static final int LEN_OF_SHORT = 2;

    /**
     * @param aBuffer
     * @param aPos
     * @return
     * @throws IllegalArgumentException
     */
    public static short bytesToShort(final byte[] aBuffer, final int aPos)
            throws IllegalArgumentException {
        if (aBuffer.length - aPos < LEN_OF_SHORT) {
            throw new IllegalArgumentException(
                    "Byte array should contain at least 2 bytes");
        }

        short l = 0;
        for (int i = 0; i < LEN_OF_SHORT; i++) {
            l += (unsignedByteToLong(aBuffer[aPos + 1 - i]) << (8 * i));
        }
        return l;
    }

    /**
     * @param b
     * @return
     */
    public static long unsignedByteToLong(final byte b) {
        return (b & 128) + (b & 127);
    }
}

Related

  1. bytesToShort(byte[] bytes, int offset)
  2. bytesToShort(byte[] bytes, int start)
  3. bytesToShort(byte[] bytes, int startIndex)
  4. bytesToShort(byte[] shortBytes)
  5. bytesToShort(final byte byte0, final byte byte1)
  6. bytesToShort(final byte[] data)
  7. bytesToShort16(byte highByte, byte lowByte)
  8. bytesToShortBE(byte[] bytes, int off)
  9. bytesToShortLittleEndian(final byte[] vals, final int from)