Get a short from 2 bytes of the given array at offset 0. - Java java.lang

Java examples for java.lang:byte Array to short

Description

Get a short from 2 bytes of the given array at offset 0.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] b = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(bytes2short(b));
    }//www  .j a  v  a  2s . c o m

    /**
     * Get a short from 2 bytes of the given array at offset 0.
     * 
     * @param  b byte array
     * @return a short
     */
    public static final short bytes2short(byte[] b) {
        return bytes2short(b, 0);
    }

    /**
     * Get a short from 2 bytes of the given array at specific offset.
     * 
     * @param b   byte array
     * @param off offset of the byte array
     * @return a short
     */
    public static final short bytes2short(byte[] b, int off) {
        return (short) ((b[off] & 0xff) << 8 | (b[off + 1] & 0xff));
    }
}

Related Tutorials