Languages
[Edit]
EN

Java - convert int to binary String

6 points
Created by:
Warren-X
443

Short solutions

In java simples way to convert integer to binary String is to use Integer.toBinaryString(number).

Simple example:

int number = 8;
String binaryString = Integer.toBinaryString(number);

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

Convert int to binary String with leading zeros:

int number = 8;

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

System.out.println(binaryString);     // 1000
System.out.println(withLeadingZeros); // 00001000

More on this topic under link:

Java - convert int to binary String with leading zeros


1. Print int and binary representation of a number

public class Example1 {

    public static void main(String[] args) {

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

        int number = 8;

        String binary = Integer.toBinaryString(number);
        String intPadding = String.format("%3s", number);

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

Output:

int | binary
  8 - 1000

2. Print int and binary representation between 0 and 8

public class Example2 {

    public static void main(String[] args) {

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

        for (int number = 0; number <= 8; number++) {

            String binary = Integer.toBinaryString(number);
            String intPadding = String.format("%3s", number);

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

Output:

int | binary
  0 - 0
  1 - 1
  2 - 10
  3 - 11
  4 - 100
  5 - 101
  6 - 110
  7 - 111
  8 - 1000

Merged questions

  1. Java - convert integer to binary String representation
  2. How to cast int to binary string in java?
  3. Java - print integer 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