Trusted answers to developer questions

How to convert an integer to binary in Java

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Introduction

There are multiple techniques for converting an integer (i) to equivalent binary representation. This article discusses the most straightforward approach.

Integer.toBinaryString(int i)

To convert an integer to binary, we can simply call thepublic static String toBinaryString(int i) method of the Integer class. This method returns the binary string that corresponds to the integer passed as an argument to this function.

Let's see a simple example

Code

See the code below for basic implementation:

import java.util.*;
class Main {
public static void main(String[] args) {
int n1 = 10;
int n2 = -15;
int n3 = 200;
String binary1 = Integer.toBinaryString(n1);
String binary2 = Integer.toBinaryString(2);
String binary3 = Integer.toBinaryString(3);
System.out.println(n1 + " in binary is: " + binary1);
System.out.println(n2 + " in binary is: " + binary2);
System.out.println(n3 + " in binary is: " + binary3);
}
}

Adding padding 0s and 4-bit block for printing

The string returned from the Integer.toBinaryString(int i) method call would not have padding by 0s.

To add the padding, first format the string to fixed-width string using the String.format() method. Then, replace spaces with 0s using the String.replaceAll(String str, String replacement).

Take a look at the code snippet below:

String.format("%32s", binaryString).replaceAll(" ", "0");

Adding 4-bit blocks

For increased readability, we can add 4-bit blocks using the following code snippet.

StringBuffer sb = new StringBuffer();
for (int i = 0; i< binaryString.length(); i++ ) {
  sb.append(binaryString.charAt(i));
  if (i%4 == 3 && i != binaryString.length() - 1)
    sb.append(separator);
}

Let’s see an example where we convert integers from 5-5 to 55 into binary. Take a look at the code below to understand this better.

import java.util.*;
class Int2Binary {
private static String binaryString;
private static void int2binary(int n) {
binaryString = Integer.toBinaryString(n);
}
private static void addPadding(){
binaryString = String.format("%32s", binaryString).replaceAll(" ", "0");
}
private static void addBlocks(String separator) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i< binaryString.length(); i++ ){
sb.append(binaryString.charAt(i));
if (i%4 == 3 && i != binaryString.length() - 1)
sb.append(separator);
}
binaryString = sb.toString();
}
public static void convert2Binary(int n) {
int2binary(n);
addPadding();
addBlocks("_");
}
public static void main(String[] args) {
int n = 10;
for (int i = -5; i <= 5; i++){
convert2Binary(i);
System.out.format("Binary representation of %2d is %s\n", i, binaryString);
}
}
}

RELATED TAGS

java
binary
Did you find this helpful?