convert bytes to short. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

convert bytes to short.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toShort(bytes));
    }/*w w  w.j a v a2s.  co m*/

    /** nbr of shift positions. */
    private static final int BYTE_SHIFT = 8;

    /**
     * convert bytes to short.
     * 
     * @param bytes
     *            bytes to convert
     * @return short given bytes as an int
     */
    public static short toShort(byte[] bytes) {
        return (short) (((-(short) Byte.MIN_VALUE + bytes[0]) << BYTE_SHIFT)
                - Byte.MIN_VALUE + bytes[1]);
    }
}

Related Tutorials