Convert Integer to Binary

2/12/2012 code-examplejava

# Summary

This program converts Integer number received from user and displays the binary form of that integer number onto the screen. This program explains the logic, but Java also provides in-built methods in java.lang package, which can be directly used in bigger projects.

# Example

Integer class provides toBinaryString(int value) static method.

# Code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package conversionprogram;

/**
 *
 * @author Rohan Sakhale
 */
public class ConversionProgram {

    /**
     * @param args the command line arguments
     */
    public static String toBinary(int num)
    {
        String result = "";
        int base = 2; // 2 states Binary Conversion
        
        // Iterate untill num is more than 0
        // On every iterate divide num by the base
        // The residue we get will be adding before our result
        while(num>0)
        {
            int residue = num % base;
            result = residue + result;
            num = num / base;
        }
        return result; // Returns the final binary string
    }

    public static void main(String[] args) {
        System.out.println("Our Binary Output: " + toBinary(102));
        System.out.println("Inbuilt Java Binary Output: " + Integer.toBinaryString(102));
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37