Converts the specified byte array to int. - Java java.lang

Java examples for java.lang:byte Array to int

Description

Converts the specified byte array to int.

Demo Code

/*/*from  w w  w  .  java 2  s  . c  o  m*/
 * Copyright (c) 2015, Alachisoft. All Rights Reserved.
 *
 * 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.
 */
//package com.java2s;
import java.nio.charset.Charset;

public class Main {
    /**
     * Converts the specified byte array to int. It is callers responsibilty to ensure that value can be converted to Int32
     *
     * @param buffer
     * @return
     */
    public static int ToInt32(byte[] buffer) throws Exception {
        int cInt = 0;
        try {
            cInt = Integer.decode(new String(buffer, Charset
                    .forName("UTF-8")));
        } catch (Exception e) {
            throw e;
        }

        return cInt;
    }

    /**
     * Convert the selected bytes to int
     *
     * @param buffer buffer containing the value
     * @param offset offset from which the int bytes starts
     * @param size number of bytes
     * @return
     */
    public static int ToInt32(byte[] buffer, int offset, int size, String s)
            throws Exception {
        int cInt = 0;
        try {
            int buffsize = 0;
            for (int i = 0; i < buffer.length; i++) {
                if (buffer[i] != 0)
                    buffsize++;
                else
                    break;
            }
            cInt = Integer.decode(new String(buffer, offset, buffsize,
                    Charset.forName("UTF-8")));
        } catch (Exception e) {
            throw e;
        }

        return cInt;
    }

    /**
     * Convert the selected bytes to int
     *
     * @param buffer buffer containing the value
     * @param offset offset from which the int bytes starts
     * @param size number of bytes
     * @return
     */
    public static int ToInt32(byte[] buffer, int offset, int size)
            throws Exception {
        int cInt = 0;
        try {
            cInt = Integer.decode(new String(buffer, offset, size, Charset
                    .forName("UTF-8")));
        } catch (Exception e) {
            throw e;
        }

        return cInt;
    }
}

Related Tutorials