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

Java examples for java.lang:byte Array to short

Description

Read an unsigned 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(readUnsignedShort(array, offset));
    }/*ww w.j a  v a2  s  .co  m*/

    /**
     * Read an unsigned short from the byte array at the given offset.
     * 
     * @param array Array to read from
     * @param offset Offset to read at
     * @return short
     */
    public final static int readUnsignedShort(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 ((b0 << 8) + (b1 << 0));
    }
}

Related Tutorials