Android Byte Array to Little Endian Convert getWord(byte[] buffer, int pos)

Here you can find the source of getWord(byte[] buffer, int pos)

Description

Convert byte to 16 bit integer.

License

Open Source License

Parameter

Parameter Description
buffer a parameter
pos a parameter

Declaration

public static int getWord(byte[] buffer, int pos) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from   ww w. j  av  a 2  s. c  o m
     * Convert byte to 16 bit integer.
     * @param buffer
     * @param pos
     * @return
     */
    public static int getWord(byte[] buffer, int pos) {
        int first = getUnsignedSafe(buffer, pos);
        int second = getUnsignedSafe(buffer, pos + 1);
        int res = second + ((first << 8) & 0x0000FF00);
        return res;
    }

    /**
     * Convert byte from byte buffer to unsigned integer.
     * @param buffer
     * @param pos : index of the byte in the buffer.
     * @return
     */
    public static int getUnsignedSafe(byte[] buffer, int pos) {
        if (null == buffer || pos >= buffer.length || pos < 0) {
            return 0;
        }
        int res = toUnsignedInteger(buffer[pos]);
        return res;
    }

    /**
     * Convert byte to unsigned integer.
     * @param b
     * @return
     */
    public static int toUnsignedInteger(byte b) {
        int n = b >= 0 ? b : b + 256;
        return n;
    }
}

Related

  1. getByteLittleEndian_unit16(byte[] theBytes, int idx)