Java Integer Create toInt(byte[] value)

Here you can find the source of toInt(byte[] value)

Description

Converte um texto representado por um arranjo de bytes em um inteiro.

License

Apache License

Parameter

Parameter Description
value arranjo.

Return

inteiro.

Declaration

public static int toInt(byte[] value) 

Method Source Code

//package com.java2s;
/*/*from  w ww  .j  a  v a2 s  . co m*/
 * BRCache http://brcache.brandao.org/
 * Copyright (C) 2015 Afonso Brandao. (afonso.rbn@gmail.com)
 *
 * 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.
 */

public class Main {
    private static final int NEGATIVE_INT = 0xffffffff;
    private static final byte ZERO = '0';
    private static final byte NEGATIVE = '-';
    private static final byte POSITIVE = '+';
    private static final byte TRUE = 1;
    private static final byte FALSE = 0;

    /**
     * Converte um texto representado por um arranjo de bytes em um inteiro.
     * @param value arranjo.
     * @return inteiro.
     */
    public static int toInt(byte[] value) {
        int limit = value.length - 1;
        byte signal = value[0] == NEGATIVE ? FALSE : TRUE;
        byte hasSignal = value[0] == NEGATIVE || value[0] == POSITIVE ? TRUE : FALSE;

        int start = hasSignal == TRUE ? 1 : 0;
        int result = 0;
        int mult = 1;

        for (int i = limit; i >= start; i--) {
            int tmp = value[i] - ZERO;
            result += tmp * mult;
            mult *= 10;
        }

        if (signal == FALSE) {
            result = (result ^ NEGATIVE_INT) + 1;
        }

        return result;
    }
}

Related

  1. toInt(byte[] res)
  2. toInt(byte[] si)
  3. toInt(byte[] src)
  4. toInt(byte[] src)
  5. toInt(byte[] src, int srcPos)
  6. toInt(byte[] value)
  7. toInt(char msc, char lsc)
  8. toInt(char[] bytes, boolean le)
  9. toInt(double d)