Decimal to Binary in Java using Loop Example code

/* The following code illustrates how to convert an Integer to Binary using loop . We can convert an Integrer to Binary in several ways . We have converted Integet to Binary in two ways . First funtion returns binary as String . IInd Function returns Binary as a integer. For returning as a string , we can easily concatenate the value of (number%2 ) in reverse order. In the second function , steps to conver integer to binary
For example, consider 10 as a integer.

1) 10 % 2 = 0 - Ist binary digit
2) 10/2 = 5
3) 5%2 = 1 - IInd binary digit
4) 5/2 = 2
5) 2%2 = 0 - IIIrd binary digit
6) 2/2 = 1
7) 1%2 = 1 - IV th binary digit

Now convert individual digitis as single number which gives the binary number.
0 + 1*10 + 0*100 + 1 * 1000 = 0+10+0+1000 = 1010 */



import java.util.Scanner;

class binaryLoop {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Please enter Integer");

int number = sc.nextInt();

String bin=binary1(number);

long bin1=binary2(number);

System.out.println("Using Function 1 : Binary of " +number + " is " + bin);
System.out.println("Using Function 2 : Binary of " +number + " is " + bin1);
}

public static String binary1 (int num)
{
int sum=0;
int temp=1;
String bin="";
if (num==0) return "0";
while (num!=0)
{
bin=(num%2)+ bin;
num=num/2;

}
return bin;
}



public static long binary2 (int num)
{

long sum=0;
long temp=1;

while (num!=0)
{
sum = sum + temp*(num%2);
temp=temp*10;
num=num/2;

}

return sum;

}

}




Output :

Running the above program

D:\as2\JF1>java binaryLoop
Please enter Integer
10
Using Function 1 : Binary of 10 is 1010
Using Function 2 : Binary of 10 is 1010

D:\as2\JF1>java binaryLoop
Please enter Integer
25
Using Function 1 : Binary of 25 is 11001
Using Function 2 : Binary of 25 is 11001

0 comments:

Post a Comment

 
Copyright 2011 Java Online