This week's programming exercise is to write a program to convert 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 their are exactly 10 digits to represent 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 has lot of use in digital world, in fact binary is 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 percentage sign
(%). This is also known as remainder operator because it returns remainder of 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
onvert a decimal number to octal and hexadecimal systems, but there are couple of more ways to do that, as shown in this
article.