Languages
[Edit]
EN

Java - convert long to binary String

13 points
Created by:
Root-ssh
6322

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.