Here you can find the source of intToBinary(long value, int bits)
Parameter | Description |
---|---|
value | Int value to be converted. |
bits | How many bits can be used . |
public static String intToBinary(long value, int bits)
//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); } }