Converting an int to a binary string representation in Java?
One more way- By using java.lang.Integer you can get string representation of the first argument i
in the radix (Octal - 8, Hex - 16, Binary - 2)
specified by the second argument.
Integer.toString(i, radix)
Example_
private void getStrtingRadix() {
// TODO Auto-generated method stub
/* returns the string representation of the
unsigned integer in concern radix*/
System.out.println("Binary eqivalent of 100 = " + Integer.toString(100, 2));
System.out.println("Octal eqivalent of 100 = " + Integer.toString(100, 8));
System.out.println("Decimal eqivalent of 100 = " + Integer.toString(100, 10));
System.out.println("Hexadecimal eqivalent of 100 = " + Integer.toString(100, 16));
}
OutPut_
Binary eqivalent of 100 = 1100100
Octal eqivalent of 100 = 144
Decimal eqivalent of 100 = 100
Hexadecimal eqivalent of 100 = 64
Integer.toBinaryString(int i)
public static string intToBinary(int n)
{
String s = "";
while (n > 0)
{
s = ( (n % 2 ) == 0 ? "0" : "1") +s;
n = n / 2;
}
return s;
}
There is also the java.lang.Integer.toString(int i, int base) method, which would be more appropriate if your code might one day handle bases other than 2 (binary). Keep in mind that this method only gives you an unsigned representation of the integer i, and if it is negative, it will tack on a negative sign at the front. It won't use two's complement.