集册 Java实例教程 将字节数组转换为int数组。

将字节数组转换为int数组。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

441
将字节数组转换为int数组。

/* 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.

 *//* 来 自 时代Java*/

//package com.nowjava;


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++) {/**来 自 n o w  j a v a  . c o m**/

            ints[i] = readInt(bytes, i << 2);

        }

        return ints;

    }


    
展开阅读全文