Home Communities
IT Knowledge
Inspiration
Languages
EN

# Java - convert long to binary String with leading zeros

11 points
Created by:
154570

Short solution:

``````long number = 10_000_000_000L;

String binaryString = Long.toBinaryString(number);
String withLeadingZeros = String.format("%64s", binaryString).replace(' ', '0');

// 1001010100000010111110010000000000
System.out.println(binaryString);

// 0000000000000000000000000000001001010100000010111110010000000000

In java simples way to convert long to binary String with leading zeros is to use `Long.toBinaryString(number)` and S`tring.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.

## 1. Convert long to binary String with leading zeros

``````public class Example1 {

public static void main(String[] args) {

long number = 8;

String binary = Long.toBinaryString(number);
String padding = String.format("%8s", binary).replace(' ', '0');

System.out.println("long | binary");
}
}``````

Output:

``````long | binary
8 - 00001000``````

## 2. Convert large long to binary String - 64 length padding

``````public class Example2 {

public static void main(String[] args) {

long number = 31L * Integer.MAX_VALUE;

String binary = Long.toBinaryString(number);
String padding = String.format("%64s", binary).replace(' ', '0');

System.out.println("long:");
System.out.println(number);
}
}``````

Output:

``````long:
66571993057
0000000000000000000000000000111101111111111111111111111111100001``````

## 3. Print long to binary - between 0 and 8 with leading zeros

``````public class Example3 {

public static void main(String[] args) {

System.out.println("long | binary");

for (long i = 0; i <= 8; i++) {

String binary = Long.toBinaryString(i);
String padding = String.format("%8s", binary).replace(' ', '0');

}
}
}``````

Output:

``````long | binary
0 - 00000000
1 - 00000001
2 - 00000010
3 - 00000011
4 - 00000100
5 - 00000101
6 - 00000110
7 - 00000111
8 - 00001000``````

## Merged questions

Join to our subscribers to be up to date with content, news and offers.