Convert a byte array back to an integer number. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Convert a byte array back to an integer number.

Demo Code

/*//  w  w w  .j  a  va  2s .  c  o  m
 * @(#) ByteArrayUtils.java
 *
 * This code is part of the JAviator project: javiator.cs.uni-salzburg.at
 * Copyright (c) 2009  Clemens Krainer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
//package com.java2s;
import java.io.ByteArrayInputStream;

import java.io.DataInputStream;

import java.io.IOException;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] a = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(bytes2int(a));
    }

    /**
     * Convert a byte array back to an integer number.
     *  
     * @param a the byte array representing the integer.
     * @return the converted number as an integer.
     * @throws IOException thrown in case of conversion errors.
     */
    public static int bytes2int(byte[] a) throws IOException {
        ByteArrayInputStream bin = new ByteArrayInputStream(a);
        DataInputStream din = new DataInputStream(bin);
        return din.readInt();
    }
}

Related Tutorials