Languages
[Edit]
EN

Java - convert long to binary String

13 points
Created by:
Root-ssh
177780

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

Merged questions

  1. Java - convert long to binary String representation
  2. How to cast long to binary string in java?
  3. Java - print long in binary format
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join