Home Communities
IT Knowledge
Inspiration
Languages
EN

# Java - convert int to binary String

6 points
Created by:
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

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);

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);

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

Join to our subscribers to be up to date with content, news and offers.