Java Bits to Int bitsToInt(String bits, int min, int max)

Here you can find the source of bitsToInt(String bits, int min, int max)

Description

Turns the bit string back into an integer.

License

Open Source License

Parameter

Parameter Description
bits the bit string (0s and 1s)
min the minimum
max the maximum

Return

the integer

Declaration

public static int bitsToInt(String bits, int min, int max) 

Method Source Code

//package com.java2s;
/*//from   ww w . ja  v a  2  s. c  om
 *   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 3 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, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Turns the bit string back into an integer.
     *
     * @param bits   the bit string (0s and 1s)
     * @param min      the minimum
     * @param max      the maximum
     * @return      the integer
     */
    public static int bitsToInt(String bits, int min, int max) {
        double j = 0;
        for (int i = 0; i < bits.length(); i++) {
            if (bits.charAt(i) == '1') {
                j = j + Math.pow(2, bits.length() - i - 1);
            }
        }
        j += min;

        return Math.min((int) j, max);
    }
}

Related

  1. bitsToInt(boolean[] pBits)
  2. bitsToIntArray(String bits, int min, int max, int numBits, int size)