Trending
Loading...
Tuesday, 21 March 2017

Decimal to binary and vice versa program in java

1)Decimal to binary conversion program

import java.util.Scanner;
public class Deci2Bin
{
public static void main(String[] args)
{
int n;
String x;
Scanner s = new Scanner(System.in);
System.out.print("Enter any decimal number:");
n = s.nextInt();
Deci2Bin obj = new Deci2Bin();
x = obj.inBinary(n);
System.out.println("Binary number:"+x);
}
String inBinary(int y)
{
int a;
if(y > 0)
{
a = y % 2;
return (binary(y / 2) + "" +a);
}
return "";
}
}


2)Binary to decimal conversion Program


import java.util.Scanner;
public class BinToDeci {

public int getDecimalFromBinary(int binary){

int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
decimal += tmp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
return decimal;
}

public static void main(String a[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter binary number(0and 1)");
int bin=sc.nextInt();
BinToDeci bd = new BinToDeci();
System.out.print("Decimal Number:"+getDecimalFromBinary(bin);
}
}

0 comments:

Post a Comment

Copyright © 2012 gogfmj All Right Reserved
Designed by Odd Themes - Published By Blogger Templates20
Back To Top