Converting an int to a binary string representation in Java?
What would be the best way (ideally, simplest) to convert an int to a binary string representation in Java?
For example, say the int is 156. The binary string representation of this would be "10011100".
Solution 1:
Integer.toBinaryString(int i)
Solution 2:
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.
Solution 3:
public static string intToBinary(int n)
{
String s = "";
while (n > 0)
{
s = ( (n % 2 ) == 0 ? "0" : "1") +s;
n = n / 2;
}
return s;
}
Solution 4:
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