How to Convert Decimal to Binary in Java
How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary.
- Using toBinaryString() method
- Using user-defined logic
public class DecimalToBinaryExample { public static void main(String args[]) { String str=Integer.toBinaryString(25); //using toBinaryString() String str1=Integer.toBinaryString(45); System.out.println("Binary representation of 25 is: "+str); System.out.println("Binary representation of 45 is: "+str1); } }Output
Binary representation of 25 is: 11001 Binary representation of 45 is: 101101
Using user defined logic
In this method, we have to define our own logic for converting decimal to binary. Example In the following example, we have defined a class DecimaltoBinary. Inside the class, we have defined toString() method which accepts an integer n and returns the corresponding binary string. The number n will be repeatedly divided by 2 until we obtain 0 and the remainder will concatenate. The string variable ‘binary’ holds the result. The while loop has the condition n>0 which will repeatedly perform the operations in the while block until n does not become 0. The body of the while loop contains three statements. The first statement finds the remainder on dividing n by 2, which is obtained by using a modulo operator. The second statement concatenates the remainder (rem) to the binary representation we have obtained so far. Note that we have written ‘rem+binary’ not ‘binary+rem.’ That’s why the last remainder will be the first bit in the binary representation. The third statement updates the value of n, i.e., it divides the value by 2 and takes the quotient. When we invoke the method toBinary() with decimal=0 (which is the special check for n==0 is not present). The variable binary will be initialized to "". The condition n!=0 is false, so the loop will not be execute even once and the result returned would be "", which is not the correct answer, the correct answer is "0". Because of this we add a special check for decimal=0.public class DecimalToBinary { public String toBinary(int n) //n is a global variable { if (n == 0) { return "0"; } String binary=""; while (n>0) { int rem = n%2; //calculates remainder binary=rem+binary; //concatenates binary in remainder n=n/2; // } return binary; //returns binary string as a result } public static void main(String[] args) { int decimal=27; //decimal is a local variable DecimalToBinary decimalToBinary = new DecimalToBinary(); //creating object of DecimalToBinary class String binary = decimalToBinary.toBinary(decimal); //function calling System.out.println("The binary representation of the number is: "+binary); } }Output
The binary representation of the number is: 11011