Tuesday, December 13, 2011

Java program to calculate binary value for a given number

import java.util.*;
import java.io.*;
class binary
{
public static void main(String args[])throws Exception
{
int i=0,sum=0;
int a[]=new int[100];
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
int k1=n;
while(n!=0)
{
a[i]=n%2;
i++;
n=n/2;
}
for(int j=i-1;j>=0;j--)
{
sum=sum*10+a[j];
}
System.out.println("Binary form of "+k1+" is:"+sum);
}
}

output:
enter a number
8
Binary form of 8 is 1000