Java Integer Create toInt(final byte b)

Here you can find the source of toInt(final byte b)

Description

Converts a byte to an integer as 2 ˆ 8 + 2 ˆ 7 + 2 ˆ 6 + 2 ˆ 5 + 2 ˆ 4 + 2 ˆ 3 + 2 ˆ 2 + 2 ˆ 1 + 2 ˆ 0

License

Open Source License

Parameter

Parameter Description
b the byte.

Return

The integer.

Declaration

public static int toInt(final byte b) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2013, 2014, 2015 QPark Consulting  S.a r.l.
 * /*from w w w .j a va 2  s .co  m*/
 * This program and the accompanying materials are made available under the 
 * terms of the Eclipse Public License v1.0. 
 * The Eclipse Public License is available at 
 * http://www.eclipse.org/legal/epl-v10.html.
 ******************************************************************************/

public class Main {
    /**
     * Converts a byte to an integer as <code>
     * 2 &circ; 8 + 2 &circ; 7 + 2 &circ; 6 + 2 &circ; 5 + 2 &circ; 4 + 2 &circ; 3 + 2 &circ; 2 + 2 &circ; 1 + 2 &circ; 0
     * </code>
     *
     * @param b
     *            the byte.
     * @return The integer.
     */
    public static int toInt(final byte b) {
        int value = 0;
        for (int i = 0; i < 8; i++) {
            if ((b & 1 << i) > 0) {
                value += Math.pow(2, i);
            }
        }
        return value;
    }

    /**
     * Returns an int. If the {@link String} is <code>null</code> or
     * {@link Integer#parseInt(String)} throws a {@link NumberFormatException}
     * it returns the defaultValue.
     *
     * @param s
     *            the {@link String}.
     * @param defaultValue
     *            the default value.
     * @return the int.
     */
    public static int toInt(final String s, final int defaultValue) {
        int i = defaultValue;
        if (s != null) {
            try {
                i = Integer.parseInt(s);
            } catch (NumberFormatException e) {
                // nothing to do
            }
        }
        return i;
    }
}

Related

  1. toInt(double[] layer)
  2. toInt(double[] v)
  3. toInt(double[][] data)
  4. toInt(double[][] doubles)
  5. toInt(final Boolean value)
  6. toInt(final byte b)
  7. toInt(final byte[] buffer, final int offset, final int length)
  8. toInt(final byte[] bytes, final int offset)
  9. toInt(final byte[] bytes, final int offset)