Header Ads

Convert Decimal to binary in java :: How i coded it

How to convert an Integer value to Binary

The math logic is something 
To convert decimal to binary is also very simple, you simply divide the decimal value by 2 and then write down the remainder, repeat this process until you cannot divide by 2 anymore, for example let's take the decimal value 157: 

157 ÷ 2 = 78---- with a remainder of 1
78 ÷ 2 = 39-----with a remainder of 0
39 ÷ 2 = 19----with a remainder of 1
19 ÷ 2 = 9-----with a remainder of 1
9 ÷ 2 = 4-----with a remainder of 1
4 ÷ 2 = 2-----with a remainder of 0
2 ÷ 2 = 1----with a remainder of 0
1 ÷ 2 = 0 ---with a remainder of 1   <--- to convert write this remainder first.

Next write down the value of the remainders from bottom to top (in other words write down the bottom remainder first and work your way up the list) which gives: 

10011101 = 157
It can be seen here

So I am going to implement this rule--

I will write a function that will take the input as a number and provide the output as a binary code.

public String deciToBinary(int num)

public String deciToBinary(int t)
t is the input variable... how to get dynamically??? Check here
//This will be my return string
 String j="";
//This c  is reminder variable
        int c=0;
 int h;
//I will operate this operation until the number( given ) becomes 0 see the last line of the above example
// h is the temporary variable to hold the initial value of the number.
//Divide the number by 2
// Check the remainder
//this is my exit criteria
                if (t!=0)
//as need to read from behind refer the above example i am creating the output by adding the current remainder (first)+the previous remainder.This will create a stack of the remainder list.
             else {
        System.out.println("val of j final--"+j);

There is one more way to do it....

say i have to determine the binary equivalent of 156...
The process is described as ....Click here for the logic

Here is the example of this method written on a piece of paper.  The steps are labeled "A" through "L".

Let me write the code for this..

public class decToBin { 
    public static void main(String[] args) {
    //y is your input variable. how to get dynamically??? Check here
    int y=9;
    // set x to the largest power of two that is <= y
    int x = 1;
    String output="";
    while (x <= y/2) {
        x = x * 2;
    // check for presence of powers of 2 in y, from largest to smallest
    while (x > 0) {

        // x is not present in y
        if (y < x) {
            //save this to the output variable

        // x is present in y, so remove x from y
        else {
        //save this to the output variable
            y = y - x;

        // Next smallest power of 2
        x = x / 2;


Powered by Blogger.