Convert an array of bytes into an array of ints. - Java File Path IO

Java examples for File Path IO:Byte Array

Description

Convert an array of bytes into an array of ints.

Demo Code

/* Copyright (c) 2011 Danish Maritime Authority.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License./*from   w  ww.ja v a 2  s  . c o m*/
 */
//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(java.util.Arrays.toString(readInts(bytes)));
    }

    /**
     * Convert an array of bytes into an array of ints. 4 bytes from the input data map to a single int in the output
     * data.
     *
     * @param bytes
     *            The data to read from.
     * @return An array of integers corresponding to the specified byte array
     * @throws IllegalArgumentException
     *             if the length of the array is not divisible by 4
     */
    public static int[] readInts(byte[] bytes) {
        if ((bytes.length & 3) != 0) { // & 3 = % 4
            throw new IllegalArgumentException(
                    "Number of bytes must be a multiple of 4.");
        }
        int[] ints = new int[bytes.length >> 2];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = readInt(bytes, i << 2);
        }
        return ints;
    }

    /**
     * Reads a int using big-endian convention from the specified offset.
     *
     * @param bytes
     *            The array to read from
     * @param offset
     *            the position to start reading from
     * @return the integer corresponding to the 4 bytes that was read
     */
    public static int readInt(byte[] bytes, int offset) {
        return (bytes[offset] << 24) + ((bytes[offset + 1] & 0xff) << 16)
                + ((bytes[offset + 2] & 0xff) << 8)
                + (bytes[offset + 3] & 0xff);
    }
}

Related Tutorials