Java Integer to Binary intToBinary(long value, int bits)

Here you can find the source of intToBinary(long value, int bits)

Description

This method converts int values to binary-string.

License

LGPL

Parameter

Parameter Description
value Int value to be converted.
bits How many bits can be used .

Return

String representation of a said Int.

Declaration

public static String intToBinary(long value, int bits) 

Method Source Code

//package com.java2s;
// This software is released under GNU Lesser General Public License 2.1.

public class Main {
    /**//from   w w  w  . ja  v a2  s .  c o m
     * This method converts int values to binary-string. intToBinary(1,2) --> "01"
     *
     * @param value Int value to be converted.
     * @param bits  How many bits can be used .
     * @return String representation of a said Int.
     */
    public static String intToBinary(long value, int bits) {
        /* if bits too few, i.e. 10,2 then result is "11" */
        char[] returnValue = new char[bits];
        boolean wasNegative = false;

        if (value < 0) {
            wasNegative = true;
            ++value;
            value = (value * -1);
        }

        for (int i = 0; i < bits; ++i) {
            returnValue[i] = '0';
        }

        for (int i = returnValue.length - 1; i > -1; --i) {
            if (value >= (int) Math.pow(2.0, i * 1.0)) {
                returnValue[returnValue.length - 1 - i] = '1';
                value = value - (int) Math.pow(2.0, i * 1.0);
            }
        }

        if (wasNegative) {
            for (int i = 0; i < returnValue.length; ++i) {
                if (returnValue[i] == '0') {
                    returnValue[i] = '1';
                } else {
                    returnValue[i] = '0';
                }
            }
        }

        return new String(returnValue);
    }
}

Related

  1. integerToBinaryString(int value, int numberOfBits)
  2. integerToBinString(final int aValue, final int aFieldWidth)
  3. intToBinary(int binary, int digits)
  4. intToBinary(int i)
  5. intToBinary(int i, int byteLength)
  6. intToBinString(int val, int width)
  7. itob(int i, int j)
  8. ItoB(int x)
  9. iToB(int[] intVals)