This week's programming exercise is to write a program to convert a decimal number to binary in Java. It's a simple exercise for beginners who has just started learning Java programming language. Decimal numbers are base 10 numbers, which means there are exactly 10 digits to represent a number, starting from 0 to 9, on the other hand, binary number system has just two digits 0 and 1, which is known as bits. Binary numbers have lot of use in the digital world, in fact, binary is the language of computers where 0 and 1 represent true/false, on/off and becomes key for logic formation. In order to convert a decimal number into binary, we will use modules operator in Java, represented by a percentage sign (%). This is also known as a remainder operator because it returns the remainder of a division operation, for example, 5%,2 will return 1 while 7%4 will return 3.

Since binary is a base 2 number system, we will divide each digit of decimal number with 2 and collect remainder. Logic of converting a decimal number to binary is encapsulated inside toBinary(int number) method, which takes a decimal number and returns a byte array containing bits of binary equivalent.

By the way you can use technique mentioned in this article to also c

##

Here is our complete Java program, which takes a decimal number as input from user and convert it to binary format, after that it display it on console. There are two methods in the code, first one is toBinary() and second one is printBinary(), former converts a decimal number to binary while later prints it. I have also created a third method called convert() which combines these two methods. Logic of how to convert a decimal to binary is written on toBinary() method, if you look that method, we first create a copy of input number, which you should always do if you intend to modify input passed by user. There is a while loop, which runs until decimal number is greater than zero. In each pass, we do two operation, first using division operator / and second using remainder operator %. In each pass number is reduced in half. Just like a/10 is used to remove last digit from number and a%10 is used to get last digit, a/20 removes last bit and a%2 gives you last bit. All these bits are stored in a byte array, whose size is 32 because size of int primitive is 32-bit in Java. PrintBinary() is a simple method to print binary array in Java.

That's all on

Complete Java Masterclass

Java Fundamentals: The Java Language

Java In-Depth: Become a Complete Java Engineer!

Since binary is a base 2 number system, we will divide each digit of decimal number with 2 and collect remainder. Logic of converting a decimal number to binary is encapsulated inside toBinary(int number) method, which takes a decimal number and returns a byte array containing bits of binary equivalent.

By the way you can use technique mentioned in this article to also c

*onvert a decimal number to octal and hexadecimal systems*, but there are couple of more ways to do that, as shown in this article.##
__Java Program to Convert Decimal to Binary__

Here is our complete Java program, which takes a decimal number as input from user and convert it to binary format, after that it display it on console. There are two methods in the code, first one is toBinary() and second one is printBinary(), former converts a decimal number to binary while later prints it. I have also created a third method called convert() which combines these two methods. Logic of how to convert a decimal to binary is written on toBinary() method, if you look that method, we first create a copy of input number, which you should always do if you intend to modify input passed by user. There is a while loop, which runs until decimal number is greater than zero. In each pass, we do two operation, first using division operator / and second using remainder operator %. In each pass number is reduced in half. Just like a/10 is used to remove last digit from number and a%10 is used to get last digit, a/20 removes last bit and a%2 gives you last bit. All these bits are stored in a byte array, whose size is 32 because size of int primitive is 32-bit in Java. PrintBinary() is a simple method to print binary array in Java.import java.util.Scanner; import java.util.concurrent.TimeUnit; /** * Java program to convert Decimal number into Binary in Java. * * @author Javin */ public class Testing { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int number = Integer.MAX_VALUE; while (number != 0) { // Ask user to enter number for decimal to binary conversion System.out.println("\nEnter a decimal number to convert into binary format"); number = sc.nextInt(); // one way to convert decimal number to binary in Java byte[] bits = toBinary(number); printBinary(bits); // combined conversion and printing part in one method convert(number); } sc.close(); } /* * Java Method to convert decimal to binary */ public static byte[] toBinary(int number) { byte[] binary = new byte[32]; int index = 0; int copyOfInput = number; while (copyOfInput > 0) { binary[index++] = (byte) (copyOfInput % 2); copyOfInput = copyOfInput / 2; } return binary; } /* * Print number in binary format */ public static void printBinary(byte[] binary) { for (int i = binary.length - 1; i >= 0; i--) { System.out.print(binary[i]); } } /* * Combination of previous two method to convert and print binary numbers */ public static void convert(int input) { int copyOfInput = input; StringBuilder sb = new StringBuilder(); while (copyOfInput > 0) { byte bit = (byte) (copyOfInput % 2); sb.append(bit); copyOfInput = copyOfInput / 2; } System.out.printf("\nDecimal number %d in Binary format is %s %n", input, sb.toString()); } }Enter a decimal number to convert into binary format 33 00000000000000000000000000100001 Decimal number 33 in Binary format is 100001 Enter a decimal number to convert into binary format 45 00000000000000000000000000101101 Decimal number 45 in Binary format is 101101Output

That's all on

**How to convert a decimal number to binary in Java**. You can write similar programs to convert decimal numbers to octal or hexadecimal format. All you need to change is core logic, where instead of dividing by 2 you need to divide by 8 or 16, depending upon whether you are converting into Octal or Hexadecimal. One more thing which you need to take care in case of base 16 is incorporating additional characters e.g. from A to F to represent 10 to 15. On reverse side if you want to convert Hexadecimal number to decimal, octal or binary, you can see this tutorial.**Further Learning**Complete Java Masterclass

Java Fundamentals: The Java Language

Java In-Depth: Become a Complete Java Engineer!

Great and Simple

ReplyDeleteHi..!! I couldn't understand below line of code:

ReplyDeleteSystem.out.printf("\nDecimal number %d in Binary format is %s %n", input, sb.toString());

like: %d, %s, %n what is this and how is it working?? is this any new feature?? if then please provide me the link where you have explained these new things..!! thanks

great thanks.!

ReplyDelete