EN
Java - convert int to binary String
6
points
Short solutions
In java simples way to convert integer to binary String is to use Integer.toBinaryString(number)
.
Simple example:
int number = 8;
String binaryString = Integer.toBinaryString(number);
System.out.println(binaryString); // 1000
Convert int to binary String with leading zeros:
int number = 8;
String binaryString = Integer.toBinaryString(number);
String withLeadingZeros = String.format("%8s", binaryString).replace(' ', '0');
System.out.println(binaryString); // 1000
System.out.println(withLeadingZeros); // 00001000
More on this topic under link:
Java - convert int to binary String with leading zeros
1. Print int and binary representation of a number
public class Example1 {
public static void main(String[] args) {
System.out.println("int | binary");
int number = 8;
String binary = Integer.toBinaryString(number);
String intPadding = String.format("%3s", number);
System.out.println(intPadding + " - " + binary);
}
}
Output:
int | binary
8 - 1000
2. Print int and binary representation between 0 and 8
public class Example2 {
public static void main(String[] args) {
System.out.println("int | binary");
for (int number = 0; number <= 8; number++) {
String binary = Integer.toBinaryString(number);
String intPadding = String.format("%3s", number);
System.out.println(intPadding + " - " + binary);
}
}
}
Output:
int | binary
0 - 0
1 - 1
2 - 10
3 - 11
4 - 100
5 - 101
6 - 110
7 - 111
8 - 1000