In: Computer Science
1.Write a Java program that inputs a binary number and displays the same number in decimal.
2.Write Java program that inputs a decimal number and displays the same number in binary.
1. Write a Java program that inputs a binary number and displays the same number in decimal.
Code:
import java.util.*;
class binaryToDecimal
{
static int binaryToDecimal(int n)
{
int num=n;
int decimalValue=0;
int base=1;
int temp=num;
while(temp>0)
{
int last_digit=temp%10;
temp=temp/10;
decimalValue=decimalValue+last_digit*base;
base=base*2;
}
return decimalValue;
}
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.print("Enter binary number to be converted to decimal:
");
int num=sc.nextInt();
System.out.print("Decimal number is: ");
System.out.println(binaryToDecimal(num));
}
}
Code Screesnhot:
Output Screenshot:
2. Write Java program that inputs a decimal number and displays the same number in binary.
Code:
import java.util.*;
class decimalToBinary
{
static void decimalToBinary(int n)
{
int[] binaryNum=new int[1000];
int i=0;
while(n>0)
{
binaryNum[i]=n%2;
n=n/2;
i++;
}
for(int j=i-1;j>=0;j--)
System.out.print(binaryNum[j]);
}
public static void main (String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.print("Enter decimal number to be converted to binary:
");
int num=sc.nextInt();
System.out.print("Binary number is: ");
decimalToBinary(num);
}
}
Code Screesnhot:
Output Screenshot: