Java Byte Array to Short bytesToShort(byte[] buffer, int index)

Here you can find the source of bytesToShort(byte[] buffer, int index)

Description

This function converts the bytes in a byte array at the specified index to its corresponding short value.

License

Open Source License

Parameter

Parameter Description
buffer The byte array containing the short.
index The index for the first byte in the byte array.

Return

The corresponding short value.

Declaration

static public short bytesToShort(byte[] buffer, int index) 

Method Source Code

//package com.java2s;
/************************************************************************
 * Copyright (c) Crater Dog Technologies(TM).  All Rights Reserved.     *
 ************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.        *
 *                                                                      *
 * This code is free software; you can redistribute it and/or modify it *
 * under the terms of The MIT License (MIT), as published by the Open   *
 * Source Initiative. (See http://opensource.org/licenses/MIT)          *
 ************************************************************************/

public class Main {
    /**/* ww  w .j  a  va 2 s. c  o  m*/
     * This function converts the bytes in a byte array to its corresponding short value.
     *
     * @param buffer The byte array containing the short.
     * @return The corresponding short value.
     */
    static public short bytesToShort(byte[] buffer) {
        return bytesToShort(buffer, 0);
    }

    /**
     * This function converts the bytes in a byte array at the specified index to its
     * corresponding short value.
     *
     * @param buffer The byte array containing the short.
     * @param index The index for the first byte in the byte array.
     * @return The corresponding short value.
     */
    static public short bytesToShort(byte[] buffer, int index) {
        int length = 2;
        short integer = 0;
        for (int i = 0; i < length; i++) {
            integer |= ((buffer[index + length - i - 1] & 0xFF) << (i * 8));
        }
        return integer;
    }
}

Related

  1. bytesToShort(byte a, byte b, boolean swapBytes)
  2. bytesToShort(byte b1, byte b2)
  3. bytesToShort(byte byte1, byte byte2)
  4. bytesToShort(byte hiByte, byte loByte)
  5. bytesToShort(byte[] buf)
  6. bytesToShort(byte[] bytes)
  7. bytesToShort(byte[] bytes)
  8. bytesToShort(byte[] bytes)
  9. bytesToShort(byte[] bytes, boolean netOrder)