How to Convert Decimal to Binary in java Without Using Library Function?

2
34
• 1
•
•
•
•
•
•
•
•
•
1
Share Convert Decimal to Binary in java Without Using Library Function?

The math logic:

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
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)
{
}
``````

The actual Decimal to Binary Conversion Code:

``````
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
while (t > 0) {
// h is the temporary variable to hold the initial value of the number.
h = t;
//Divide the number by 2
t = (h / 2);
// Check the remainder
c = h % 2;
//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.
j = Integer.toString(c) + j;
} else {
j = Integer.toString(h) + j;
}
}
System.out.println("val of j final--" + j);
}
``````

There is one more way to do it

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
output = output + "0";
}

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

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

System.out.println(output);
}
}
``````
Don't miss out!

Receive top technical news, lesson ideas, travel tips and more!

Give it a try. You can unsubscribe at any time.

• 1
•
•
•
•
•
•
•
•
•
1
Share