Here you can find the source of toInteger(byte[] b)
Parameter | Description |
---|---|
b | A 4 bytes array. |
Parameter | Description |
---|---|
NullPointerException | b is null. |
IllegalArgumentException | The length of b is not 4. |
public static int toInteger(byte[] b)
//package com.java2s; /*//ww w. j a v a 2 s. c om * Copyright (c) 2015 NEC Corporation * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html */ public class Main { /** * The number of octets in an integer value. */ public static final int NUM_OCTETS_INTEGER = Integer.SIZE / Byte.SIZE; /** * A mask value which represents all bits in a byte value. */ public static final int MASK_BYTE = (1 << Byte.SIZE) - 1; /** * The number of bits to be shifted to get the first octet in an integer. */ private static final int INT_SHIFT_OCTET1 = 24; /** * The number of bits to be shifted to get the second octet in an integer. */ private static final int INT_SHIFT_OCTET2 = 16; /** * The number of bits to be shifted to get the third octet in an integer. */ private static final int INT_SHIFT_OCTET3 = 8; /** * Convert a 4 bytes array into an integer number. * * @param b A 4 bytes array. * @return An integer number. * @throws NullPointerException * {@code b} is {@code null}. * @throws IllegalArgumentException * The length of {@code b} is not 4. */ public static int toInteger(byte[] b) { if (b.length != NUM_OCTETS_INTEGER) { throw new IllegalArgumentException("Invalid byte array length: " + b.length); } int index = 0; int value = (b[index++] & MASK_BYTE) << INT_SHIFT_OCTET1; value |= (b[index++] & MASK_BYTE) << INT_SHIFT_OCTET2; value |= (b[index++] & MASK_BYTE) << INT_SHIFT_OCTET3; return value | (b[index] & MASK_BYTE); } /** * Convert the given number into a {@link Integer} instance. * * @param num A {@link Number} instance. * @return An {@link Integer} instance equivalent to the given number. * {@code null} if {@code num} is {@code null}. */ public static Integer toInteger(Number num) { return (num == null) ? null : Integer.valueOf(num.intValue()); } }