EN
Java - convert long to binary String with leading zeros
11 points
Short solution:
xxxxxxxxxx
1
long number = 10_000_000_000L;
2
3
String binaryString = Long.toBinaryString(number);
4
String withLeadingZeros = String.format("%64s", binaryString).replace(' ', '0');
5
6
// 1001010100000010111110010000000000
7
System.out.println(binaryString);
8
9
// 0000000000000000000000000000001001010100000010111110010000000000
10
System.out.println(withLeadingZeros);
In java simples way to convert long to binary String with leading zeros is to use Long.toBinaryString(number)
and String.format()
method.
Note that as first param in String format we pass number of leading spaces and we replace all spaces with 0. Usually we use 32 or 64 padding zeros.
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 padding = String.format("%8s", binary).replace(' ', '0');
9
String numberPadding = String.format("%4s", number);
10
11
System.out.println("long | binary");
12
System.out.println(numberPadding + " - " + padding);
13
}
14
}
Output:
xxxxxxxxxx
1
long | binary
2
8 - 00001000
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
String padding = String.format("%64s", binary).replace(' ', '0');
9
10
System.out.println("long:");
11
System.out.println(number);
12
System.out.println("binary (64 length padding):");
13
System.out.println(padding);
14
}
15
}
Output:
xxxxxxxxxx
1
long:
2
66571993057
3
binary (64 length padding):
4
0000000000000000000000000000111101111111111111111111111111100001
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
5
System.out.println("long | binary");
6
7
for (long i = 0; i <= 8; i++) {
8
9
String binary = Long.toBinaryString(i);
10
String padding = String.format("%8s", binary).replace(' ', '0');
11
String intPadding = String.format("%4s", i);
12
13
System.out.println(intPadding + " - " + padding);
14
}
15
}
16
}
Output:
xxxxxxxxxx
1
long | binary
2
0 - 00000000
3
1 - 00000001
4
2 - 00000010
5
3 - 00000011
6
4 - 00000100
7
5 - 00000101
8
6 - 00000110
9
7 - 00000111
10
8 - 00001000