Java Integer to Binary integerToBinaryString(int value, int numberOfBits)

Here you can find the source of integerToBinaryString(int value, int numberOfBits)

Description

Converts a value from a normal integer to a binary value of type String.

License

Open Source License

Parameter

Parameter Description
value value to turn from integer into binary string
numberOfBits the number of bits to return

Return

a completed binary string

Declaration

public static String integerToBinaryString(int value, int numberOfBits) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from w w  w.jav a2  s.  c o m*/
     * Converts a value from a normal integer to a binary value of type String.
     * @param value value to turn from integer into binary string
     * @param numberOfBits the number of bits to return
     * @return a completed binary string
     */
    public static String integerToBinaryString(int value, int numberOfBits) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(Integer.toBinaryString(value));

        // Adds 0's to the front of the binary if the string does not come out as expected.
        while (stringBuilder.length() != numberOfBits) {
            String old = stringBuilder.toString();
            stringBuilder = new StringBuilder();
            stringBuilder.append("0" + old);
        }

        String finalizedBinaryValue = stringBuilder.toString();
        return finalizedBinaryValue;
    }
}

Related

  1. int2binString(int x)
  2. integerToBin(int value)
  3. integerToBinaryString(int value)
  4. integerToBinString(final int aValue, final int aFieldWidth)
  5. intToBinary(int binary, int digits)
  6. intToBinary(int i)
  7. intToBinary(int i, int byteLength)