EN
Java - convert long to binary String
13
points
In java simples way to convert long to binary String is to use Long.toBinaryString(number)
.
Simple example:
long number = 10_000_000_000L;
String binaryString = Long.toBinaryString(number);
System.out.println(binaryString); // 1001010100000010111110010000000000
1. Convert long to binary String
public class Example1 {
public static void main(String[] args) {
long number = 8;
String binary = Long.toBinaryString(number);
String numberPadding = String.format("%4s", number);
System.out.println("long | binary");
System.out.println(numberPadding + " - " + binary);
}
}
Output:
long | binary
8 - 1000
2. Convert large long to binary String
public class Example2 {
public static void main(String[] args) {
long number = 31L * Integer.MAX_VALUE;
String binary = Long.toBinaryString(number);
System.out.println(" long | binary");
System.out.println(number + " - " + binary);
}
}
Output:
long | binary
66571993057 - 111101111111111111111111111111100001
3. Print long converted to binary String representation between 0 and 8
public class Example3 {
public static void main(String[] args) {
System.out.println("long | binary");
for (long number = 0L; number <= 8L; number++) {
String binary = Long.toBinaryString(number);
String numberPadding = String.format("%4s", number);
System.out.println(numberPadding + " - " + binary);
}
}
}
Output:
long | binary
0 - 0
1 - 1
2 - 10
3 - 11
4 - 100
5 - 101
6 - 110
7 - 111
8 - 1000