Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

Java - convert long to binary String

0 contributions
13 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more