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:
xxxxxxxxxx
1
long number = 10_000_000_000L;
2
String binaryString = Long.toBinaryString(number);
3
4
System.out.println(binaryString); // 1001010100000010111110010000000000
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
5
long number = 8;
6
7
String binary = Long.toBinaryString(number);
8
String numberPadding = String.format("%4s", number);
9
10
System.out.println("long | binary");
11
System.out.println(numberPadding + " - " + binary);
12
}
13
}
Output:
xxxxxxxxxx
1
long | binary
2
8 - 1000
xxxxxxxxxx
1
public class Example2 {
2
3
public static void main(String[] args) {
4
5
long number = 31L * Integer.MAX_VALUE;
6
7
String binary = Long.toBinaryString(number);
8
9
System.out.println(" long | binary");
10
System.out.println(number + " - " + binary);
11
}
12
}
Output:
xxxxxxxxxx
1
long | binary
2
66571993057 - 111101111111111111111111111111100001
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
5
System.out.println("long | binary");
6
7
for (long number = 0L; number <= 8L; number++) {
8
9
String binary = Long.toBinaryString(number);
10
String numberPadding = String.format("%4s", number);
11
12
System.out.println(numberPadding + " - " + binary);
13
}
14
}
15
}
Output:
xxxxxxxxxx
1
long | binary
2
0 - 0
3
1 - 1
4
2 - 10
5
3 - 11
6
4 - 100
7
5 - 101
8
6 - 110
9
7 - 111
10
8 - 1000