Languages
[Edit]
EN

Java - convert long to binary String with leading zeros

11 points
Created by:
Root-ssh
68600

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
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.

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');
        String numberPadding = String.format("%4s", number);

        System.out.println("long | binary");
        System.out.println(numberPadding + " - " + padding);
    }
}

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);
        System.out.println("binary (64 length padding):");
        System.out.println(padding);
    }
}

Output:

long:
66571993057
binary (64 length padding):
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');
            String intPadding = String.format("%4s", i);

            System.out.println(intPadding + " - " + padding);
        }
    }
}

Output:

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

Merged questions

  1. Java - convert long to binary String representation with leading zeros
  2. How to cast long to binary string with padding to 64 digits in java?
  3. Java - print long in binary format with leading zeros
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join