Reads a int using big-endian convention from the specified offset. - Java java.lang

Java examples for java.lang:int Binary

Description

Reads a int using big-endian convention from the specified offset.

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./*w w  w .  j  av  a 2  s  .  com*/
 */
//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 };
        int offset = 2;
        System.out.println(readInt(bytes, offset));
    }

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