Read a short from the byte array at the given offset. - Java java.lang

Java examples for java.lang:byte Array to short

Description

Read a short from the byte array at the given offset.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] array = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int offset = 2;
        System.out.println(readShort(array, offset));
    }/*from w w w.  jav a  2s  . c om*/

    /**
     * Read a short from the byte array at the given offset.
     * 
     * @param array Array to read from
     * @param offset Offset to read at
     * @return (signed) short
     */
    public final static short readShort(byte[] array, int offset) {
        // First make integers to resolve signed vs. unsigned issues.
        int b0 = array[offset + 0] & 0xFF;
        int b1 = array[offset + 1] & 0xFF;
        return (short) ((b0 << 8) + (b1 << 0));
    }
}

Related Tutorials