Java Array Unpack unpackIntegerByWidth(int len, byte[] buf, int offset)

Here you can find the source of unpackIntegerByWidth(int len, byte[] buf, int offset)

Description

Unpack a big endian integer, of a given length, from a byte array.

License

Open Source License

Parameter

Parameter Description
len length of integer to pull out of buffer
buf source array to get bytes from
offset position to start at in buf

Return

The unpacked integer

Declaration

private static int unpackIntegerByWidth(int len, byte[] buf, int offset) 

Method Source Code

//package com.java2s;
/**//www .j  av a 2s  . c om
 * Copyright (C) 2009-2013 FoundationDB, LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Unpack a big endian integer, of a given length, from a byte array.
     * @param len length of integer to pull out of buffer
     * @param buf source array to get bytes from
     * @param offset position to start at in buf
     * @return The unpacked integer
     */
    private static int unpackIntegerByWidth(int len, byte[] buf, int offset) {
        if (len == 1) {
            return buf[offset];
        } else if (len == 2) {
            return (buf[offset] << 24 | (buf[offset + 1] & 0xFF) << 16) >> 16;
        } else if (len == 3) {
            return (buf[offset] << 24 | (buf[offset + 1] & 0xFF) << 16 | (buf[offset + 2] & 0xFF) << 8) >> 8;
        } else if (len == 4) {
            return buf[offset] << 24 | (buf[offset + 1] & 0xFF) << 16 | (buf[offset + 2] & 0xFF) << 8
                    | (buf[offset + 3] & 0xFF);
        }

        throw new IllegalArgumentException("Unexpected length " + len);
    }
}

Related

  1. unpackBCD(byte[] source)
  2. unpackDie(byte[] bytes)
  3. UnpackFloat(byte[] bytes, float value)
  4. UnpackFloatBuffer(byte[] buffer, long bytes_read, long num_loaded, float[] list)
  5. unpackInt(byte[] data, int offset)
  6. unpackLE(long aValue, byte[] aBuf, int aOffset)
  7. UnpackLittle32(byte[] bytes, int integer)
  8. unpackLittleEndianLong(byte[] bytes)
  9. unpackLong(byte[] arr, int i, int j)