Languages
[Edit]
EN

Java - convert int to binary String

6 points
Created by:
AnnLen
1771

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

Java conversion

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.