Java Integer to Bit intToBits(int in, int min, int max, int numBits)

Here you can find the source of intToBits(int in, int min, int max, int numBits)

Description

Turns an integer into a bitstring (0s and 1s).

License

Open Source License

Parameter

Parameter Description
in the integer to convert
min the minimum
max the maximum
numBits the number of bits

Return

the bit string

Declaration

public static String intToBits(int in, int min, int max, int numBits) 

Method Source Code

//package com.java2s;
/*/*from   w w w .  jav a  2s  .  com*/
 *   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 an integer into a bitstring (0s and 1s).
     *
     * @param in      the integer to convert
     * @param min      the minimum
     * @param max      the maximum
     * @param numBits   the number of bits
     * @return      the bit string
     */
    public static String intToBits(int in, int min, int max, int numBits) {
        in = in - min;
        in = Math.min(in, max - min);
        String bits = Integer.toBinaryString(in);
        while (bits.length() < numBits)
            bits = "0" + bits;
        return bits;
    }
}

Related

  1. convertIntToBits(int num)
  2. convertIntToBitsWithPadding(int num)
  3. intToBits(int n, int size)
  4. intToBits(int no)
  5. intToBits(int pInt, boolean[] pBits)