Solved ProgramsISCClass 11Computer Science

Decimal to Binary Conversion in Java: 3 Programs with Examples

How to convert a decimal number to binary on paper and in Java: three programs (String, place value and Integer.toBinaryString), binary to decimal, a dry run and common mistakes.

5 min read
Solved Programs

Converting a decimal number to binary is one of the first programs ISC Class 11 students write in the number systems chapter, and ICSE Class 10 students meet it as a loop program. This post shows the method on paper first, then three Java programs: with a String, with place values, and with the library method, plus the reverse conversion from binary to decimal.

What binary means

Decimal numbers use ten digits (0–9) and each place is worth ten times the place to its right: units, tens, hundreds. Binary numbers use only two digits, 0 and 1, and each place is worth twice the place to its right: 1, 2, 4, 8, 16, 32 and so on. Computers store everything in binary because a circuit can easily be on (1) or off (0).

Decimal to binary on paper: repeated division by 2

Divide the number by 2 again and again, writing down each remainder, until the quotient becomes 0. The binary number is the remainders read from bottom to top. For 25:

2 | 25    remainder 1   (least significant bit)
2 | 12    remainder 0
2 |  6    remainder 0
2 |  3    remainder 1
2 |  1    remainder 1   (most significant bit)
     0
Reading the remainders from bottom to top: 25 = (11001) base 2

Check it by multiplying each digit by its place value: 1×16 + 1×8 + 0×4 + 0×2 + 1×1 = 25.

Program 1: decimal to binary using a String

Each remainder num % 2 is the next binary digit from the right, so it is added to the left of the string. This version works for every non-negative int, because a String has no size limit.

import java.util.*;

class DecimalToBinary
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int n = sc.nextInt();

        if (n == 0)
        {
            System.out.println("Binary = 0");
            return;
        }
        int num = n;
        String bin = "";
        while (num > 0)
        {
            int rem = num % 2;      // remainder is the next binary digit
            bin = rem + bin;        // add it to the left
            num = num / 2;
        }
        System.out.println("Binary of " + n + " = " + bin);
    }
}

Output:

Enter a decimal number: 25
Binary of 25 = 11001

Program 2: decimal to binary using place values

Many textbooks build the answer as a number that looks like binary, by multiplying each remainder by 1, 10, 100, 1000 and so on. A long is used because the result grows quickly: 1023 already needs ten digits (1111111111), and an int overflows for numbers above 1023.

import java.util.*;

class DecToBinLong
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int n = sc.nextInt();

        long bin = 0;     // binary digits stored as a decimal-looking number, e.g. 11001
        long place = 1;   // 1, 10, 100, 1000 ...
        int num = n;
        while (num > 0)
        {
            int rem = num % 2;
            bin = bin + rem * place;
            place = place * 10;
            num = num / 2;
        }
        System.out.println("Binary of " + n + " = " + bin);
    }
}

Program 3: using Integer.toBinaryString()

Java's wrapper class Integer can do the conversion in one line. Use it to check your answers, but in the exam write the loop unless the question allows library methods.

class LibraryBinary
{
    public static void main(String[] args)
    {
        int n = 25;
        String bin = Integer.toBinaryString(n);       // "11001"
        int back = Integer.parseInt("11001", 2);       // 25
        System.out.println(n + " in binary = " + bin);
        System.out.println("11001 in decimal = " + back);
        System.out.println("25 in octal = " + Integer.toOctalString(n) + ", in hexadecimal = " + Integer.toHexString(n));
    }
}

Output:

25 in binary = 11001
11001 in decimal = 25
25 in octal = 31, in hexadecimal = 19

Binary to decimal

To go back, start with 0 and, for each binary digit from left to right, multiply the running total by 2 and add the digit. For 11001: 0×2+1 = 1, 1×2+1 = 3, 3×2+0 = 6, 6×2+0 = 12, 12×2+1 = 25. The program also rejects any digit that is not 0 or 1.

import java.util.*;

class BinaryToDecimal
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a binary number: ");
        String bin = sc.next();

        int dec = 0;
        for (int i = 0; i < bin.length(); i++)
        {
            char ch = bin.charAt(i);
            if (ch != '0' && ch != '1')
            {
                System.out.println("Invalid binary number");
                return;
            }
            dec = dec * 2 + (ch - '0');   // shift left one place and add the new digit
        }
        System.out.println("Decimal value = " + dec);
    }
}

Dry run of Program 1 for n = 13

num   num % 2   bin
13    1         "1"
6     0         "01"
3     1         "101"
1     1         "1101"
0     -         loop ends, so 13 = 1101

Variable description

  • n — int — the decimal number entered by the user
  • num — int — working copy of n that is divided by 2
  • rem — int — remainder of num % 2, the next binary digit
  • bin — String — the binary digits built so far

Common mistakes

  • Adding each new digit to the right of the string, which prints the binary number backwards.
  • Forgetting that 0 needs its own case: the while loop never runs for 0.
  • Using an int for the place-value method, which overflows for numbers above 1023.
  • Changing n itself inside the loop and then printing n, which by then is 0.

Practice questions

  1. Convert 45, 100 and 255 to binary by hand, then check them with Program 1.
  2. Modify Program 1 to count how many 1s are in the binary form of a number.
  3. Write a program to convert a decimal number to octal (divide by 8 instead of 2).
  4. Write a program that accepts a binary number and prints whether it is even or odd without converting it.

For the theory behind conversions between binary, octal and hexadecimal, read Number Systems for ISC Class 11, and watch the decimal and binary lesson in the video tutorials.