Share
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
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);}}
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");
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 to 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);}}}